var timeout = null;

function covetLoad(){
	jQuery('body').append('<div id="flashnotice" style="display:none;"></div>');
	jQuery('body').append('<div id="flasherrors" style="display:none;"></div>');

	if (window.location.href.match(/\/products\//)){
		var list_key = getCovetListKey();
		var list_id = getCovetListID();
	
		jQuery.ajax({
			url: "http://www.williamlang.net/ajax/Covet/List.php?id="+covet_key+"&c="+list_key+"&j=?",
			type: "GET",
			dataType: "jsonp",
			jsonp: 'j',
			success: (function(data){
				var productHandle = getProductHandle();			
				var items = data.items;
				var productInWishlist = false;
				
				for (var i = 0; i < items.length; i++){
					if (items[i].handle == productHandle){
						productInWishlist = true;
						break;
					}
				}
				
				if (jQuery('#covet_wishlist_button').length > 0){
					if (productInWishlist){
						jQuery('#covet_wishlist_button').val('Remove from Wishlist');
						jQuery('#covet_wishlist_button').unbind();
						jQuery('#covet_wishlist_button').click(function(){ removeFromWishlist(); return; });	
					}else{
						jQuery('#covet_wishlist_button').unbind();
						jQuery('#covet_wishlist_button').click(function(){ addToWishlist(); return; });
					}
				}
				
				if (jQuery('#covet_add_to_wishlist').length > 0){
					if (productInWishlist){
						jQuery('#covet_add_to_wishlist').hide();	
						jQuery('#covet_remove_from_wishlist').show();
						jQuery('#covet_add_to_wishlist').unbind();
						jQuery('#covet_remove_from_wishlist').click(function(){ removeFromWishlist(); return; });
					}else{
						jQuery('#covet_add_to_wishlist').unbind();
						jQuery('#covet_add_to_wishlist').click(function(){ addToWishlist(); return; });
					}
				}				
			}),
		});	
	}
}

jQuery(document).ready(function(){
	covetLoad();
});

function removeFromWishlist(){
	var list_key = getCovetListKey();
	var list_id = getCovetListID();	
	var productHandle = getProductHandle();
		
	jQuery.ajax({
		url: "/products/" + productHandle + ".js",
		type: "GET",
		dataType: "json",
		success: (function(data){
			var currentProduct = data.id;				
			var list_key = getCovetListKey();
			var list_id = getCovetListID();		
			
			jQuery.ajax({
				url: "http://www.williamlang.net/ajax/Covet/Delete.php?id="+covet_key+"&c="+list_key+"&k_id="+list_id+"&p=" + currentProduct + "&j=?",
				type: "GET",
				dataType: "jsonp",
				jsonp: 'j',
				success: (function(data){
					covetSuccess(data);
				}),
			});
		}),
	});
	
	return;
}

function addToWishlist(){
	var list_key = getCovetListKey();
	var list_id = getCovetListID();
	var productHandle = getProductHandle();
	
	jQuery.ajax({
		url: "/products/" + productHandle + ".js",
		type: "GET",
		dataType: "json",
		success: (function(data){
			var currentProduct = data.id;
			var list_key = getCovetListKey();						
			
			jQuery.ajax({
				url: "http://www.williamlang.net/ajax/Covet/Add.php?id="+covet_key+"&c="+list_key+"&k_id="+list_id+"&p=" + currentProduct + "&j=?",
				type: "GET",
				dataType: "jsonp",
				jsonp: 'j',
				success: (function(data){
					covetSuccess(data);
				}),
			});
		}),
	});
	
	return;
}

function covetSuccess(data){
	var status = data.status;
	var key = data.k;
	var id = data.k_id;

	if (status){
		if (status == "Product Added"){
			if (getCovetListKey() == "") createCookie('covet_list_key', key, 365);
			if (getCovetListID() == "") createCookie('covet_list_id', id, 365);			
			
			if (jQuery('#covet_wishlist_button').length > 0){
				jQuery('#covet_wishlist_button').val('Remove from Wishlist');
				jQuery('#covet_wishlist_button').unbind();
				jQuery('#covet_wishlist_button').click(function(){ removeFromWishlist(); return; });	
			}
			
			if (jQuery('#covet_add_to_wishlist').length > 0){
				jQuery('#covet_add_to_wishlist').hide();	
				jQuery('#covet_remove_from_wishlist').show();		
				jQuery('#covet_add_to_wishlist').unbind();
				jQuery('#covet_remove_from_wishlist').click(function(){ removeFromWishlist(); return; });
			}	
						
			notice(status);
		}
		else if (status == "Product Removed"){
			if (jQuery('#covet_wishlist_button').length > 0){
				jQuery('#covet_wishlist_button').val('Add to Wishlist');
				jQuery('#covet_wishlist_button').unbind();
				jQuery('#covet_wishlist_button').click(function(){ addToWishlist(); return; });	
			}
			
			if (jQuery('#covet_add_to_wishlist').length > 0){
				jQuery('#covet_add_to_wishlist').show();	
				jQuery('#covet_remove_from_wishlist').hide();
				jQuery('#covet_add_to_wishlist').unbind();
				jQuery('#covet_add_to_wishlist').click(function(){ addToWishlist(); return; });
			}		
			
			notice(status);
		}else{
			error(status);	
		}				
	}		
}

function createCookie(name, value, days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

function getCovetListKey(){
	var c = getURLParam('c');
	if (c != "") return c;
	if (readCookie('covet_list_key') != null) return readCookie('covet_list_key');
	return "";	
}

function getCovetListID(){
	if (readCookie('covet_list_id') != null){
		if (getCovetListKey() != "") return readCookie('covet_list_id');
		return "";
	}else{
		return "";	
	}
}

function getProductHandle(){
	var location = window.location.href;
	var regex = new RegExp(/\/products\/(.+?)$/);
	var matches = regex.exec(location);
	return matches[0].replace(/\/products\//, '');
}

function loadWishlist(){
	var list_key = getCovetListKey();
	var hn = window.location.hostname;
	var regex = new RegExp(/(.gif|.jpg|.jpeg|.png)/);
	var loopText = '';

	jQuery.ajax({
		url: "http://www.williamlang.net/ajax/Covet/List.php?id="+covet_key+"&c="+list_key+"&j=?",
		type: "GET",
		dataType: "jsonp",
		jsonp: 'j',
		success: (function(data){
			var loopText = 'empty';
			var wishlist = jQuery('#covet_wishlist');
			var wishlistLoop = wishlist.html();
			var items = data.items;
			var productInWishlist = false;
			
			for (var i = 0; i < items.length; i++){
				loopText = wishlistLoop;
				
				loopText = loopText.replace(/\[hostname\]/g, hn);
				loopText = loopText.replace(/\[product_id\]/g, items[i].id);
				
				var image = 'http://static.shopify.com/s/images/admin/no-image-large.gif';
				var matches = regex.exec(items[i].image);
				if (matches != null){
					image = items[i].image;
					image = image.replace(matches[0], '_small' + matches[0]);
				}
				
				loopText = loopText.replace(/\[product_image\]/g, image);				
				loopText = loopText.replace(/\[product_name\]/g, items[i].name);
				loopText = loopText.replace(/\[product_handle\]/g, items[i].handle);
				
				wishlist.append(loopText);
			}
			
			wishlist.html(wishlist.html().replace(wishlistLoop, ''));
			if (getURLParam('c') != ""){
				jQuery('.removeWishlist').remove();
				jQuery('#share_wishlist').remove();
			}
			if (items.length > 0) jQuery('#covet_div').slideDown();
		})
	});
}

function removeProductFromWishlist(product_id){

	var currentProduct = product_id;				
	var list_key = getCovetListKey();
	var list_id = getCovetListID();
	
	jQuery.ajax({
		url: "http://www.williamlang.net/ajax/Covet/Delete.php?id="+covet_key+"&c="+list_key+"&k_id="+list_id+"&p=" + currentProduct + "&j=?",
		type: "GET",
		dataType: "jsonp",
		jsonp: 'j',
		success: (function(data){
			if (data.status == "Product Removed"){
				jQuery('#covet_product_' + product_id).fadeOut();
				notice('Product Removed');
			}else{
				error(data.status);	
			}
		}),
	});
}

function notice(message){
	clearTimeout(timeout);
	jQuery('#flashnotice').html(message);
	jQuery('#flashnotice').fadeIn('slow', function(){
		timeout = setTimeout("jQuery('#flashnotice').fadeOut('slow');", 4000);
	});
}

function error(message){
  
  if (message == "Invalid List ID"){
    eraseCookie('covet_list_id');
    eraseCookie('covet_list_key');
  }
  
  clearTimeout(timeout);
	jQuery('#flasherrors').html('<!-- -->');
	jQuery('#flasherrors').append(message);
	jQuery('#flasherrors').fadeIn('slow', function(){
		timeout = setTimeout("jQuery('#flasherrors').fadeOut('slow');", 4000);
	});
}

function shareWishlist(){
	var hn = window.location.hostname;
	var list_key = getCovetListKey();

	var div = document.createElement('div');
	div.className = 'covet_popup';
	div.style.display = 'none';
	div.setAttribute('id', 'covet_popup');
	
	var div2 = document.createElement('div');
	div2.className = 'covet_popup_inset';
	div2.innerHTML = '<span style="float:right;margin-right:2px"><a href="#" onclick="jQuery(\'#covet_popup\').fadeOut(\'slow\', function(){ jQuery(\'#covet_popup\').remove(); });">X</a></span>';
	
	div2.innerHTML += '<h1>Share My Wishlist</h1>';
	div2.innerHTML += '<br /><h2>Facebook</h2><a href="http://www.facebook.com/sharer.php?u=http://' + hn + '/pages/wishlist?c=' + list_key + '&t=My wishlist">Share</a>';
	div2.innerHTML += '<br /><h2>Link</h2><a href="http://' + hn + '/pages/wishlist?c=' + list_key + '">http://' + hn + '/pages/wishlist?c=' + list_key + '</a>';

	div.appendChild(div2);	
	document.body.appendChild(div);
	jQuery('#covet_popup').fadeIn();
}


function getURLParam(name){
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp(regexS);
  var results = regex.exec(window.location.href);
  if (results == null){
    return "";
  }else{
    return results[1];
  }
}
