window.colehaan = window.colehaan || {} 
var randkey = $.cookie('wishlist');
var domain = "http://www.colehaan.com/jp/"
var api = "http://www.colehaan.co.jp/wishlist/api/";
colehaan.wishlist = { login: domain + "wishlist_login.html", detail: domain + "wishlist.html" }
colehaan.bitly = { login: 'chjrootcom', apiKey: 'R_41992aa404459a987f7a43deaa1c6630', format: 'json'}

function query(){
  var obj = {}, params = location.search.substring(1);
  if(params != ""){
    params = params.split("&");
    for(var i in params){
      var t = params[i].split('=');
      obj[t[0]] = t[1];
    }     
  }
  return obj;
}

$(function(){
  var datas, wishlist = $('.btn-wishlist>a');
  // Wishlist Print
  $('#btn-print').click(function(){
		var q = query(), page = q.page || 1;
		var html = 'wishlist_print.html?page=' + page;
		location = html;
  	return false;
  })
  
	// Product Print
	$('#pupprint').click(function(){
		location = 'detail_temp_print.html' + location.search;
		return false;
	})
  
  // Wishlist Controller
  if(randkey){
    wishlist.attr('href',colehaan.wishlist.detail);
    $.getJSON(api+'pull.php?callback=?',{ key: randkey },function(response){
      if(response){
        datas = response;
        $('.wishlist-count').text('('+ (datas.count||"0") +')');
      }
    })
  } else {
    wishlist.attr('href',colehaan.wishlist.login);
  }
  //Login Action
  $("#loginSubmit").click(function(){
    var email = $('#emailaddress').val();
    if(email){
      $.getJSON(api+'login.php?callback=?',{ email: email },function(response){
        if(response && response.status){
          $.cookie('wishlist',response.key);
          location.href = document.referrer
        } else {
          flashMessage('.errortxt','メールアドレスが登録されていません。');
        }
      })
    } else {
      flashMessage('.errortxt','正しく入力してください。');
    }
    return false;
  })
  // Wishlist Add Action
  $('.wishlist>a').click(function(){
    if(randkey){
        var itemId = $('.price>.prodname').text(), itemName = $('.namestyle').text();
        $.getJSON(api+'push.php?callback=?',{ key: randkey, itemId: itemId, itemName: itemName},function(response){
          if(response && response.status){
            $('.message-select').text('に追加されました。');
						$('.wishlist-count').text('(' + (response.count||0) + ')' );
          } else {
            $('.message-select').text('に追加済みです。');
          }
          $('.alert-message').css({visibility:'visible'})
        })
    } else {
      location.href = colehaan.wishlist.login;
    }
    return false;
  })
    
  // Detail View
  if($('#wl-table').length && randkey ){
    var count, allItems, max = 10;
    var page = (query().page)? query().page:1;
    $.get('xml/all.xml',{t:new Date().getTime()},function(response){
      allItems = response;
      $.getJSON(api+'pull.php?callback=?',{key:randkey},function(response){
        $('#count').text(response.count);
        count = response.count;
				$('.number').text(count||0);
        for(var i=0; i<Math.ceil(response.count/max); i++){
          var a = $('<a/>',{href:'?page='+(i+1)}).append(function(){
            return $('<img />',{ src: '', alt: '', width: 26, height: 28 })
          });
          if(i+1==page){
            $('img',a).attr('src', 'img/page' + (i+1) + '_current.gif');
          } else {
            $('img',a).attr('src', 'img/page' + (i+1) + '.gif');
          }
          $('.pagenate').append(a);
        }
        if(response.drops.length){
          var droplist = [], flash = $('.items');
          $(response.drops).each(function(){ droplist.push(this.itemName+"<br/>") });
          flash.html(droplist.join('') + "はホームページの掲載が終了したため、WISHLISTから削除されました。");
          flash.fadeIn(1000,function(){
            setTimeout(function(){ flash.fadeOut(1000) },3000);
           }) 
          $('#delete-iteam').fadeIn(1000);;
           
          // backend drop item delete        
          $.getJSON(api+'dropitems.php?callback=?',{'key':randkey},function(response){
          })
         
        }
        $(response.datas.slice((page-1)*max,page*max)).each(domCreate);  
      })
		})
  }
  
  function domCreate(){
    var html = '<td class="itemimage"><a href="#"><img src="" alt="" width="100" height="100"></a></td><td class="itemname"><h3><a href="#"></a></h3><ul><li>style # <span class="product_id"></span></li><li>color : <span class="product_color"></span></li></ul></td><td class="actionbuttons"><p><a href="#" class="tweet"><img src="img/wishlist/icon_twitter.gif" alt="" width="18" height="14" class="vamiddle">この商品についてつぶやく</a></p><p><a href="#" class="wishlist_delete"><img src="img/wishlist/icon_delete.gif" alt="" width="18" height="14">削除する</a></p></td><td class="itemprice"></td><td class="itemdate"></td>';
    var obj = $(allItems).find('product[id='+this.itemId+']');
    if(obj.length){
      if(obj.length>1) obj =obj[0];
      var id = $('style',obj).text(), name = $('name',obj).text();
      var path = $(obj).parent().attr('name');
      var tr = $('<tr />').attr('id',id).html(html)
      path = itemPath(path.split('_'),id);
      $('.itemimage a',tr).attr('href',path);
      $('.itemimage img',tr).attr('src','img/product/angle/'+ id +'.jpg');
      $('.itemname h3 a',tr).text(name).attr('href',path);
      $('.itemname .product_id',tr).text(id);
      $('.itemname .product_color',tr).text($('cname',obj).text());
      $('.itemprice',tr).text('￥'+$('price',obj).text());
      $('.itemdate',tr).text(this.created_at);
      $('.tweet',tr).attr({rel: id, title: name, href: path }).click(tweet);
      $('.wishlist_delete',tr).attr({rel: id, title: name }).click(itemRemove);
      $('#wl-table').append(tr);
    }
  }
	
	$('#popupmail').click(function(){		
		var bitly = 'http://api.bit.ly/v3/shorten?callback=?&' + $.param(colehaan.bitly);
		var product_id = $('.price .prodname').text();
    $.getJSON(bitly ,{ longUrl: location.href}, function(response){
      if(response && response.status_code == 200){
				var params = "key="+ randkey +"&bitly="+ encodeURI(response.data.url) + "&item=" + product_id;
				var html = '<iframe id="send-email" frameborder="0" src="http://www.colehaan.co.jp/wishlist/mail.php?'+ params +'" hspace="0" style="width:100%; height:100%; background:#c8c3bb;"></iframe>'
				$('#wl-email-hidden').append(html)
    		$('#wl-email-hidden').fadeIn(800);
      }
    })
		return false;
	})
  
  function flashMessage(selector,msg){
    $(selector).text(msg).show();
    setTimeout(function(){
      $(selector).hide().text('')
    },1500);  
  }
  
  function itemPath(pA,product_id){
    var str = domain + 'product/detail_temp.html?';
    str += $.param({ cat: pA[0], scat: pA[1], mid: pA[2], product: product_id });
    return str;
  }
  
  function tweet(){
    var that = this; 
    var bitly = 'http://api.bit.ly/v3/shorten?callback=?&' + $.param(colehaan.bitly);
    $.getJSON(bitly ,{ longUrl: that.href}, function(response){
      if(response && response.status_code == 200){
        location.href = 'http://twitter.com/home/?status=' +encodeURIComponent(that.title + ' ' + response.data.url);
      }
    })
    return false;
  }

  function itemRemove(){
    var that = this; 
    $.getJSON(api+'delete.php?callback=?',{ key:randkey, itemId:that.rel },function(response){
      if(response && response.status){
        var flash = $('.items'); 
        $('#'+that.rel).fadeOut(1000,function(){$(this).remove()});
        count = parseInt(count,10) - 1
        $('.wishlist-count').text("("+ count +")");
				$('.number').text(count);
        flash.text(that.title + "はWISHLISTから削除されました。");
        flash.fadeIn(1000,function(){
          setTimeout(function(){ flash.fadeOut(1000) },3000);
        })
      }
    })
    return false;
  }
  
  $('.tweet').click(function(){
    var title = $('.info .namestyle').text(), product_id = $('.info .prodname').text(), q = query();
    var url = "http://" + location.hostname + location.pathname + "?";
    var bitly = 'http://api.bit.ly/v3/shorten?callback=?&' + $.param(colehaan.bitly);
    if(q.product == product_id ) q.product = product_id;
    url += $.param(q);
    $.getJSON(bitly, {longUrl: url },function(response){
      if(response && response.status_code == 200){
        location.href = 'http://twitter.com/home/?status=' +encodeURIComponent(title + ' ' + response.data.url);
      }
    })
    return false;
  })
  
  $('#btn-email').click(function(){
		var html = '<iframe id="send-email" frameborder="0" src="http://www.colehaan.co.jp/wishlist/form.php?key='+ randkey +'" hspace="0" style="width:100%; height:100%; background:#c8c3bb;"></iframe>'
		$('#wl-email-hidden').append(html)
    $('#wl-email-hidden').fadeIn(800);
    return false;
  })
   
  $('#wl-email-hidden .btn-close').click(function(){
    $('#wl-email-hidden').fadeOut(800,function(){
			$('#send-email').remove();
		});
    return false;
  })  
})
