var getDOLUrl = "/designtools/main/ajaxSetupSession";
var storeDOLSessionUrl = "/store/storeDOLSession";
var updateItemDOLUrl = "/store/updateItemDOL";
var removeItemsDOLUrl = "/store/cartDeleteItems";
var dolSessionId;
var dolDocumentIdString;
var dolObjects;
var dolDocumentIdList;
var existingDOLSessionId;
var launchedFromCart = false;
var getDOLSession = false;

var DOLReturnFunction = function returnMethod(dolSessionId, dolItemsJSON, returnAction){
		$('dtBody').innerHTML = "";
		dolPopup.hide();
		
		if(returnAction.toUpperCase() == 'CANCEL' && launchedFromCart == false){
			var newRemoveItemsDOLUrl = removeItemsDOLUrl;
			newRemoveItemsDOLUrl += "/market/" + $F('marketId');
			
			var tempJSON;
			var itemsToRemoveIdsArray = "[{shoppingItemId:'";
		    var isFirst = true;
		    var len = dolItemsJSON.length;
		    if(len > 0){
		        for(var i=0; i<len; i++){
		        	tempJSON = dolItemsJSON[i];
		        	if(!isFirst){
		        		itemsToRemoveIdsArray += ",";
		        	}
		        	itemsToRemoveIdsArray += tempJSON.shoppingItemId;
		    		isFirst = false;
		        }
		    }
		    itemsToRemoveIdsArray += "'}]";
			
		    newRemoveItemsDOLUrl += "?removeItemArray=" + itemsToRemoveIdsArray;
			new Ajax.Request(newRemoveItemsDOLUrl, {
				method: 'post',
				onSuccess: function(request) {
		    		doOnRemoveSuccess(request.responseJSON, cartRowToRemove);
		    	}
		    });
		} else if(returnAction.toUpperCase() == 'APPROVE'){
			var newUpdateItemDOLUrl = updateItemDOLUrl;
			newUpdateItemDOLUrl += "/market/" + $F('marketId');
			newUpdateItemDOLUrl += "?dolJSONArray=" + YAHOO.lang.JSON.stringify(dolItemsJSON);
			new Ajax.Request(newUpdateItemDOLUrl, {
				method: 'get',
				onSuccess: function(request) {
					goToCart();
		    	},
		    	onFailure: function(request) {
	                doOnGetDOLFailure(request.responseText);
	            }
		    });
		} else if(returnAction.toUpperCase() == 'ERROR'){
			alert('There was an error loading Design Studio.');
			goToCart();
		}
};

function loadDOL(dolSessionId, dolItemsJSON, isLoggedIn, skipViewStateValidation){
	var isFormEmpty = true;
	if($('editTextForm') != null){
		isFormEmpty = checkImprintFormEmpty()
	}
	
	existingDOLSessionId = '';
	
	if(dolSessionId != '' && dolSessionId != undefined){
		existingDOLSessionId = dolSessionId;
	}
	
	if(isFormEmpty){
		dolObjects = dolItemsJSON;
		dolDocumentIdList = createDOLDocumentIdList(dolItemsJSON, true);
		newGetDOLUrl = getDOLUrl;
		if(existingDOLSessionId != '' && existingDOLSessionId != undefined){
			newGetDOLUrl += "/dtSessionId/" + encodeURIComponent(existingDOLSessionId);
		} else {
			newGetDOLUrl += "/dtSessionId/NEW-SESSION";
		}
		if(getDOLSession){
			if(dolDocumentIdList.length > 0){
				newGetDOLUrl += "/dtDocumentId/NEW-DOCUMENT-FROM-TEMPLATE";
				newGetDOLUrl += "/dtTemplateId/" + dolDocumentIdList;
			} else {
				newGetDOLUrl += "/dtDocumentId/EMPTY-DOCUMENT-LIST";
			}
			
			new Ajax.Request(newGetDOLUrl, {
				method: 'get',
				onSuccess: function(request) {
		    		doOnGetDOLSuccess(request.responseText, dolItemsJSON, isLoggedIn, skipViewStateValidation);
		    	},
		    	onFailure: function(request) {
	                doOnGetDOLFailure(request.responseText);
	            }
		    });
		} else {
			//Navigate to cart if nothing is DOL
			goToCart();
		}
	}
}

function createDOLDocumentIdList(dolItemsJSON, includeImprints){
	getDOLSession = false;
	dolDocumentIdArray = new Array();
	var dolItemsLength = dolItemsJSON.length;
	var dolDocumentIdList = "";
	for(var i = 0; i<dolItemsLength; i++){
		if(dolItemsJSON[i].itemType.toUpperCase() == "DOL" || (includeImprints && dolItemsJSON[i].itemType.toUpperCase() == "IMPRINT")){
			getDOLSession = true;
		}
		if(dolItemsJSON[i].itemType.toUpperCase() == "DOL"){
			dolDocumentIdList += dolItemsJSON[i].templateStylecode + ",";
		}
	}
	
	if(dolDocumentIdList.length > 0){
		dolDocumentIdList = dolDocumentIdList.substr(0, dolDocumentIdList.length - 1);
	}
	
	return dolDocumentIdList;
}

function populateDOLItemsJSONDocumentIds(dolItemsJSON, dolDocumentIds){
	var dolItemsLength = dolItemsJSON.length;
	var dolDocumentIdsArray = dolDocumentIds.split(",");
	var j = 0;
	for(var i = 0; i<dolItemsLength; i++){
		if(dolItemsJSON[i].itemType.toUpperCase() == "DOL"){ //TODO: Uncomment this when imprints work || dolItemsJSON[i].itemType.toUpperCase() == "IMPRINT"){
			dolItemsJSON[i].documentId = dolDocumentIdsArray[j];
			j++;
		}
	}
	
	return dolItemsJSON;
}

function doOnGetDOLSuccess(responseText, dolItemsJSON, isLoggedIn, skipViewStateValidation){
	if(responseText.trim() != ""){
		dolSessionId = responseText.split(":")[0];
	
		dolDocumentIdString = responseText.split(":")[1];
		
		//Store the DOL sesion id so photos are saved regardless of outcome of tool
		if(existingDOLSessionId == "" || existingDOLSessionId == undefined){
			existingDOLSessionId = dolSessionId;
			var newStoreDOLSessionUrl  = storeDOLSessionUrl;
			newStoreDOLSessionUrl += "/market/" + $F('marketId');
			newStoreDOLSessionUrl += "/dolSessionId/" + encodeURIComponent(dolSessionId);
		}
		
		new Ajax.Request(newStoreDOLSessionUrl, {
	            method: 'get'            
	        });
	    
		//Put DOL Document Id's in JSON
		if(dolDocumentIdString != "EMPTY-DOCUMENT-LIST"){
			dolItemsJSON = populateDOLItemsJSONDocumentIds(dolItemsJSON, dolDocumentIdString)
		}
		openDOLPanel(dolSessionId, dolItemsJSON, DOLReturnFunction, isLoggedIn, skipViewStateValidation);
	} else {
		alert('There was a problem launching design studio.');
		goToCart();
	}
}

function openDOLPanel(dolSessionId, dolItemsJSON, returnFunction, isLoggedIn, skipViewStateValidation){
	$('dtBody').innerHTML = "";
	if(dolPopup == null){
		dolPopup =  new YAHOO.widget.Panel("dtPanel",   
			{ width:"940px", 
				xy: [10,10],
				close:false,  
				draggable:false,  
				zindex:15, 
				modal:true, 
				visible:false 
			}  
		);
	}	
	$('dtPanel').show();
	dolPopup.render();
	dolPopup.show();	
	
	window.scroll(0,0);
	
	dtInit("dtBody", dolSessionId, dolItemsJSON, true, returnFunction, $F('marketId'), skipViewStateValidation);
}

function doOnGetDOLFailure(responseText){
    //alert('There was a problem launching the Design Studio tool');
    goToCart();
}

function checkImprintFormEmpty(){
	var hasData = false;
	if($('editTextForm')){
		var formInputs = $('editTextForm').getInputs('text');
		var len = formInputs.length;
		for(var i = 0; i<len; i++){
			if($F(formInputs[i]) != ""){
				hasData = true;
				break;
			}	
		}
	}
	
	if(hasData && formChanged){
		return (confirm("Form data will be lost\n\nData entered in the personalization form will not be carried over to the personalization tool.\nDo you want to continue?"));
	} else {
		new Effect.Fade($('imprintForm'), {duration: 0.3, queue: 'front'});
		new Effect.Appear($('useImprintForm'), {duration: 0.3, queue: 'end'});
		return true;
	}
	
}

function showImprintButton() {
	if(checkImprintFormEmpty()){
		new Effect.Fade($('imprintForm'), {duration: 0.3, queue: 'front'});
		new Effect.Appear($('useImprintForm'), {duration: 0.3, queue: 'end'});
		return true;
	} else {
		return false;
	}
}

function showImprintForm() {
	new Effect.Fade($('useImprintForm'), {duration: 0.3, queue: 'front'});
	new Effect.Appear($('imprintForm'), {duration: 0.3, queue: 'end'});
}

function goToCart(){
	var cartURL = '/store/cartDisplay/market/' + $F('marketId');;
	window.location = cartURL;
}

function moveToIcebox(dolItemsJSON){
	var moveToIceboxURL = '/store/moveItemsToIcebox/market/' + $F('marketId');;
	
	var tempJSON;
	var itemsToMoveIdsArray = "[{itemsToMoveIds:'";
    var isFirst = true;
    var len = dolItemsJSON.length;
    if(len > 0){
        for(var i=0; i<len; i++){
        	tempJSON = dolItemsJSON[i];
        	if(!isFirst){
        		itemsToMoveIdsArray += ",";
        	}
        	itemsToMoveIdsArray += tempJSON.shoppingItemId;
    		isFirst = false;
        }
    }
    itemsToMoveIdsArray += "'}]";
	
    moveToIceboxURL += "?itemsToMoveJSONArray=" + itemsToMoveIdsArray;
    new Ajax.Request(moveToIceboxURL, {
		method: 'post'
    });

}

function moveToCart(dolItemsJSON){
	var moveToCartURL = '/store/moveItemsToCart/market/' + $F('marketId');;
	
	var tempJSON;
	var itemsToMoveIdsArray = "[{itemsToMoveIds:'";
    var isFirst = true;
    var len = dolItemsJSON.length;
    if(len > 0){
        for(var i=0; i<len; i++){
        	tempJSON = dolItemsJSON[i];
        	if(!isFirst){
        		itemsToMoveIdsArray += ",";
        	}
        	itemsToMoveIdsArray += tempJSON.shoppingItemId;
    		isFirst = false;
        }
    }
    itemsToMoveIdsArray += "'}]";
	
    moveToCartURL += "?itemsToMoveJSONArray=" + itemsToMoveIdsArray;
    new Ajax.Request(moveToCartURL, {
		method: 'post'
    });

}

function submitLogin(){
	var form = $('login_form');
	if(form != null){
		var submitLocation = form.action;
		var inputs = form.getInputs();
		submitLocation += "?1=1";
		for(var j=0; j<inputs.length; j++){
			submitLocation += "&" + inputs[j].name + "=" + $F(inputs[j]);
		}
		
		new Ajax.Request(submitLocation, {
			method: 'post',
			onSuccess: function(response) {
	    		doOnSubmitLoginSuccess(response);
	    	}
	    });
	}
}

function doOnSubmitLoginSuccess(response){
	if(response.responseJSON != null){
		dtSaveDocuments(true, function() {});
	} else {
		$('dtLoginPanelContent').innerHTML = response.responseText;
	}
}

function submitRegister(){
	var form = $('register');
	if(form != null){
		var submitLocation = form.action;
		var inputs = form.getInputs();
		submitLocation = submitLocation.split("?")[0];
		submitLocation += "?1=1";
		for(var j=0; j<inputs.length; j++){
			submitLocation += "&" + inputs[j].name + "=" + inputs[j].value;
		}
		
		new Ajax.Request(submitLocation, {
			method: 'post',
			onSuccess: function(response) {
	    		doOnSubmitRegisterSuccess(response);
	    	}
	    });
	}
}

function doOnSubmitRegisterSuccess(response){
	if(response.responseJSON != null){
		dtSaveDocuments(true, function() {});
	} else {
		$('dtLoginPanelContent').innerHTML = response.responseText;
	}
}





/*********************/
/***    DOL Help   ***/
/*********************/

var helpPopup;
var getHelpUrl = "/dtcontent/help/help.html";

function openHelp(){
	
	new Ajax.Updater($('helpBody'), getHelpUrl, {
		method: 'post',evalScripts: 'true',
		onSuccess: function(request) {
    		setTimeout('renderHelpPanel()', 300);
    	}
    });
}

function renderHelpPanel(){
	// Initialize the temporary Panel to display while waiting for external content to load
	helpPopup =  new YAHOO.widget.Panel("helpPanel",   
		{ width:"660px",  
			fixedcenter:true,  
			close:false,  
			draggable:false,  
			zindex:100, 
			modal:true, 
			visible:false 
		}  
	); 

	helpPopup.render(document.body);
	helpPopup.show();
}

function loadHelp(fileNameRoot){
	new Ajax.Updater($('dtHelpContent'), "/dtcontent/help/" + fileNameRoot + "Help.html", {
		method: 'post',evalScripts: 'true'
    });
}

function setFormChanged(){
	formChanged = true;
}