var iceboxInitializeUrl = "/store/initializeIcebox/";
var iceboxAddUrl = "/store/addItemToIcebox/";
var iceboxRemoveUrl = "/store/removeItemFromIcebox/";
var itemId;
var itemDesc;
var itemStyleCode;
var itemThumbnail;
var itemSize;
var itemDetailsLink;
var icebox;

function Icebox(){
	this.empty = true;
	this.open = false;
}

function initializeIcebox(marketId){
	icebox = new Icebox();
		
	var initializeIceboxUrl = iceboxInitializeUrl + "market/" + marketId;
	new Ajax.Request(initializeIceboxUrl, {
		method: 'post', 
		evalJSON: true,
		onSuccess: function(request) {
    		updateIceboxPreviewFromJSONObject(request.responseJSON,false);
    	}
    });
}

function addToIcebox(marketId, productId){
	var addToIceboxUrl = iceboxAddUrl + "market/" + marketId + "/productId/" + productId;
	new Ajax.Request(addToIceboxUrl, {
		method: 'post', 
		onSuccess: function(request) {
    		updateIceboxPreviewFromJSONObject(request.responseJSON,true);
    	}
    });
}

function updateIceboxPreviewFromJSONObject(productsJSONObject,showIcebox){
	var len = productsJSONObject.productList.length;
	var product;
	if(len > 0){
		for(var i=0;i<len;i++){
			product = productsJSONObject.productList[i];
			itemId = product.id;
			itemDesc = product.description;
			itemStyleCode = product.styleCode;
			itemThumbnail = product.thumbnailSrc;
			itemSize = product.size;
			itemDetailsLink = product.detailsLink;
			
			addRowToIceboxPreview(itemId,itemDesc,itemStyleCode,itemThumbnail,itemSize,itemDetailsLink,showIcebox);
		}
	} else if(!productsJSONObject.isEmpty){
		icebox.open = true;
		$('iceboxEmpty').hide();
		$('iceboxPreview').show();
		Effect.BlindDown($('iceboxPreviewContainer'),{duration: 0.4});
		$('moreHideImage').src = "/free-wedding-tools/images/hide_arrow.png";
		setTimeout('toggleIcebox()', 3000);
	} else if (productsJSONObject.isEmpty) {
		$('iceboxEmpty').show();
		$('iceboxPreview').hide();
	}
}

function addRowToIceboxPreview(newItemId,newItemDesc,newItemStyleCode,newItemThumbnail,newItemSize,newItemDetailsLink,showIcebox){
	var newRowHtml = "<tr id='icebox_" + newItemId + "'>" + 
						"<td class='iceboxItemPreviewImg'>" + 
							"<a class='iceboxItemDetailsLink' href='" + newItemDetailsLink + "'>" + 
							"<img src='" + newItemThumbnail + "'/>" + 
							"</a>" + 
						"</td>" + 
						"<td class='iceboxItemDesc'>" + 
							"<a class='iceboxItemDetailsLink' href='" + newItemDetailsLink + "'>" + newItemDesc + "</a>" + 
							"<br/>" + 
							"<br/>" + 
							"Size: " + newItemSize + 
							"<br/>" + 
							"Style Code: " + newItemStyleCode +  
						"</td>" + 
						"<td class='iceboxItemRemove'>" + 
							"<div class='iceboxItemRemoveDiv' onclick='removeFromIcebox(" + newItemId + ")'>" + 
								"<img src='/web_images/b_remove_icon.gif'/>" + 
								"<br/>" + 
								"remove" + 
							"</div>" + 
						"</td>" + 
					  "</tr>";
					  
	$('iceboxItemsTBody').insert({bottom: newRowHtml});
	
	icebox.empty = false;
	$('iceboxEmpty').hide();
	$('iceboxPreview').show();
	
	if(showIcebox && icebox.open == false){
		icebox.open = true;
		//Effect.BlindDown($('showHideIcebox'), {duration: 0.4});
		Effect.BlindDown($('iceboxPreviewContainer'),{duration: 0.4, queue: 'end'});
		$('moreHideImage').src = "/free-wedding-tools/images/hide_arrow.png";
		setTimeout('toggleIcebox()', 3000);
	}
}

function toggleIcebox(){
	if(icebox.open){
		//new Effect.BlindUp($('showHideIcebox'), {duration: 0.4});
		Effect.BlindUp($('iceboxPreviewContainer'),{duration: 0.4});
		$('moreHideImage').src = "/free-wedding-tools/images/more_arrow.png";
		icebox.open = false;
	} else {
		//new Effect.BlindDown($('showHideIcebox'), {duration: 0.4});
		Effect.BlindDown($('iceboxPreviewContainer'),{duration: 0.4});
		$('moreHideImage').src = "/free-wedding-tools/images/hide_arrow.png";
		icebox.open = true;
	}
}

function removeFromIcebox(productId){
	var removeToIceboxUrl = iceboxRemoveUrl + "productId/" + productId;
	new Ajax.Request(removeToIceboxUrl, {method: 'get', contentType: 'application/xml', onSuccess: function(transport) {
		hideIceboxItem(productId);
    }});
}

function hideIceboxItem(productId){
	var productRow = $('icebox_' + productId);
	var tbl = $('iceboxItemsTBody');
	for(var j=0; j<tbl.rows.length; j++){
		var tempRow = tbl.rows[j];
		if(tempRow.id == productRow.id){
			new Effect.Fade(tempRow, {duration: 0.4});
			setTimeout('removeIceboxItem(' + productId + ')', 600);
			break;
		}
	}
}

function removeIceboxItem(productId){
	var tbl = $('iceboxItemsTBody');
	var productRow = $('icebox_' + productId);
	tbl.removeChild(productRow);
	if(tbl.childNodes.length < 1){
		icebox.empty = true;
		new Effect.BlindDown($('iceboxEmpty'), {duration: 0.4});
		new Effect.BlindUp($('iceboxPreview'), {duration: 0.4});
		setTimeout('toggleIcebox()', 3000);
	}
}

function getItemInformation(itemId){
	var newGetItemInfoUrl = "/store/getShareItemInfo/market/" + $F('marketId');
	newGetItemInfoUrl += "/itemId/" + itemId;
	new Ajax.Request(newGetItemInfoUrl, {
		onSuccess: function(request) {
			populateField('shareDesignItemJSON', YAHOO.lang.JSON.stringify(request.responseJSON));
		}
	});
}

function populateField(inputId, newValue){
	$(inputId).value = newValue;
}






/**************************************/
/****** Update/Remove Cart Items ******/
/**************************************/
var iceboxRemoveItemUrl = "/store/iceboxDeleteItems";

var tempRow;
function removeItemFromIcebox(itemId, cartRowToRemove){
	if(confirm("Are you sure you would like to remove this saved work?")){
		newIceboxRemoveItemUrl = iceboxRemoveItemUrl + "/market/" + $F('marketId');
		var tbl = $('cartSummaryTable');
		
		if(itemId != null){	
			var removeItemJSON = "[{shoppingItemId:" + itemId + "}]";
			newIceboxRemoveItemUrl += "?removeItemArray=" + removeItemJSON;
			new Ajax.Request(newIceboxRemoveItemUrl, {
				method: 'post',
				onSuccess: function(request) {
		    		doOnIceboxRemoveSuccess(request.responseJSON, cartRowToRemove);
		    	}
		    });
		}
	}
}

function doOnIceboxRemoveSuccess(JSONObject, cartRowToRemove){
	if(JSONObject != null && JSONObject.status == "success"){
		tempRow = $('cartRow_' + cartRowToRemove);
		tempRow2 = $('cartRow_' + cartRowToRemove + '_0');
		tempRowProducts = $('cartRow_' + cartRowToRemove + '_1');
		if(tempRow != null){
			new Effect.Fade(tempRow, {duration: 0.4, queue: 'parallel'});
		}
		if(tempRow2 != null){
			new Effect.Fade(tempRow2, {duration: 0.4, queue: 'parallel'});
		}
		if(tempRowProducts != null){
			new Effect.Fade(tempRowProducts, {duration: 0.4, queue: 'parallel'});
		}
		
		setTimeout('removeIceboxTempRows()', 750);
		
		if(JSONObject.isEmpty == true){
			new Effect.Fade($('cart'), {duration: 0.4, queue: 'parallel'});
			new Effect.Appear($('emptyCart'), {duration: 0.4, queue: 'parallel'});
		}		
	} else {
		var errStr = "There was an error removing the item from the cart.";
		if(JSONObject != null){
			errStr = JSONObject.message;
		}
	}
}

function removeIceboxTempRows(){
	if(tempRow != null){
		tempRow.remove();
	}

	if(tempRowProducts != null){
		tempRowProducts.remove();
	}
}


function getShortenedLink(dolJSON){
	var newGetSendLinkUrl = "/store/getShareDesignURL/market/" + $F('marketId');
	var linkParams = "dolInfoJSON=" + dolJSON;
	linkParams += "&name=" + $F('linkFromName');
	linkParams += "&linkMessage=" + $F('linkMessage');
	newGetSendLinkUrl += "?linkParams=" + linkParams + "";
	if(dolJSON != null && dolJSON != "" && $F('linkFromName') != ""){
		new Ajax.Request(newGetSendLinkUrl, {
			onSuccess: function(request) {
			populateField('linkURL', request.responseJSON.shortenedUrl);
			sendLink();
			}
		});
	}
}

function viewLargerSharedImage(dolSessionId, dolDocumentId){
	var sharedImage = $('sharedDesignImageLarge');
	sharedImage.src = "/designtools/main/ajaxGetDTDocPreviewImage/dtSessionId/" + dolSessionId + "/dtDocumentId/" + dolDocumentId + "/dtPageNumber/1/r/" + Math.random();
	var SIpopup =  new YAHOO.widget.Panel("shareDesignImagePanel",   
			{ 	xy: [10,10], 
				close:true,  
				draggable:false,  
				zindex:100, 
				modal:true, 
				visible:false 
			}  
		);
	
	SIpopup.render(document.body);
	$('shareDesignImagePanel').show();
	SIpopup.show();
	
}

/*******************/
/******* DOL *******/
/*******************/
var dolPopup = null;
var iceboxRowToUpdate;
var iceboxUpdateItemDOLUrl = "/store/updateItemDOL";
var iceboxDOLItemImageUrl = "/designtools/main/ajaxGetDTDocXSImage/dtSessionId/__DOL_SESSION_ID__/dtDocumentId/__DOL_DOC_ID__/dtPageNumber/1/";
var iceboxDOLItemPDFUrl = "/designtools/main/ajaxGetDTDocProofFile/dtSessionId/__DOL_SESSION_ID__/dtDocumentId/__DOL_DOC_ID__/";
var DOLItemId = -1;
var gblJSONTest;

var iceboxDOLReturnFunction = function iceboxOnDOLFinish(dolSessionId, dolItemsJSON, returnAction){
	gblJSONTest = dolItemsJSON;
	
	$('dtBody').innerHTML = "";
	dolPopup.hide();
	
	if(returnAction.toUpperCase() == 'APPROVE'){
		var newUpdateItemDOLUrl = iceboxUpdateItemDOLUrl;
		newUpdateItemDOLUrl += "/market/" + $F('marketId');
		newUpdateItemDOLUrl += "?dolJSONArray=" + YAHOO.lang.JSON.stringify(dolItemsJSON);
		new Ajax.Request(newUpdateItemDOLUrl, {
			method: 'get',
			onSuccess: function(request) {
				window.location.reload();
	    	},
	    	onFailure: function(request) {
                doOnIceboxDOLFailure(request.responseText);
            }
	    });
		
		var dolItemsLength = dolItemsJSON.length;
		for(var i = 0; i<dolItemsLength; i++){
			if(dolItemsJSON[i].itemType.toUpperCase() == "DOL"){ 
				var newIceboxDOLItemImageUrl = iceboxDOLItemImageUrl;
		        newIceboxDOLItemImageUrl += "r/" + (Math.random() * 100);
		        newIceboxDOLItemImageUrl = newIceboxDOLItemImageUrl.replace("__DOL_SESSION_ID__", dolSessionId);
		        newIceboxDOLItemImageUrl = newIceboxDOLItemImageUrl.replace("__DOL_DOC_ID__", dolItemsJSON[i].documentId);
		        $('dolImage_' + dolItemsJSON[i].documentId).src = newIceboxDOLItemImageUrl;
		        
				var newIceboxDOLItemPDFUrl = iceboxDOLItemPDFUrl;
		        newIceboxDOLItemPDFUrl += "r/" + (Math.random() * 100);
		        newIceboxDOLItemPDFUrl = newIceboxDOLItemPDFUrl.replace("__DOL_SESSION_ID__", dolSessionId);
		        newIceboxDOLItemPDFUrl = newIceboxDOLItemPDFUrl.replace("__DOL_DOC_ID__", dolItemsJSON[i].documentId);
		        if($('dolPDF_' + dolItemsJSON[i].documentId) != null){
		        	$('dolPDF_' + dolItemsJSON[i].documentId).href = newIceboxDOLItemPDFUrl;
				}
				if(dolItemsJSON[i].userDesignNotes != null && dolItemsJSON[i].userDesignNotes != ""){
		        	$('dolNoteDiv_' + dolItemsJSON[i].documentId).show();
		        	$('dolNote_' + dolItemsJSON[i].documentId).innerHTML = dolItemsJSON[i].userDesignNotes;
		        } //TODO: Uncomment this when imprints work else if(dolItemsJSON[i].itemType.toUpperCase() == "IMPRINT"){
			}
		}
    } else if(returnAction.toUpperCase() == 'SAVE'){
		var newUpdateItemDOLUrl = updateItemDOLUrl;
		newUpdateItemDOLUrl += "/market/" + $F('marketId');
		newUpdateItemDOLUrl += "?dolJSONArray=" + YAHOO.lang.JSON.stringify(dolItemsJSON);
		new Ajax.Request(newUpdateItemDOLUrl, {
			method: 'get',
			onFailure: function(request) {
                doOnGetDOLFailure(request.responseText);
            }
	    });
	}
};

function iceboxEditDOLItem(dolSessionId, itemId, isLoggedIn){
	launchedFromCart = true;
	getDOLItemJSON(dolSessionId, itemId, isLoggedIn, iceboxDOLReturnFunction);
}
