dojo.require("dojo.lang.*");
dojo.require("dojo.io.*");
dojo.require("wc.render.*");

ShopCart=
{
	//contextChanged boolean
	//		 indicating if an context change happened
	//isHistory boolean
	//		 indicating if the refresh are caused by browser back/forward event.
	contextChanged:false, 
	isHistory:false,
	busy:false,
	
	langId: "100",
	storeId: "",
	catalogId: "",
	orderItemId: "",
	count: "",
	itemDisplayURL: "",
	bookReviewsURL: "",
	stateSet: false,
	firstClick: false,
	itemId: "",
	
	setCommonParameters:function(langId,storeId,catalogId){
		// summary		: This function initializes common parameters used in all service calls
		// description	: This function initializes storeId, catalogId, and langId.
		// langId	: The language id to use.
		// storeId : The store id to use.
		// catalog : The catalog id to use.
		this.langId = langId;
		this.storeId = storeId;
		this.catalogId = catalogId;
	},
	
	setItemId: function(itemId)
	{
		ShopCart.itemId = itemId;
	},
	
	getItemId: function()
	{
		return ShopCart.itemId;
	},
	
	loadContentAndAddBookmark:function(workAreaModeValue, controllerId, contextId, resultPageURL)
	{

		///////////////////////////////////////////////////////////////////
		// summary: This function loads the content from the view for a given URL.
		// Description: This function will take the "resultPageURL" as input attribute, 
		// and will sets the coresponding view content to the "RefreshArea".
		//////////////////////////////////////////////////////////////////			
		cursor_wait();
		
		//Set where the user has come from if necessary
		if (!ShopCart.firstClick)
        {
        	ShopCart.setHistoryTracker(workAreaModeValue);
        	ShopCart.firstClick = true;
        }
		//Set the new page into the refresh area
		wc.render.getRefreshControllerById(controllerId).url = resultPageURL;
		wc.render.updateContext(contextId, {workAreaMode:workAreaModeValue});
		
		//Set bookmark to what was loaded
		var historyObject = new
		ShopCart.HistoryTracker(workAreaModeValue, controllerId, contextId, resultPageURL);
        dojo.undo.browser.addToHistory(historyObject);
	},
	
	loadContentFromURL:function(workAreaModeValue, controllerId, contextId, resultPageURL)
	{
		//Cannot set book mark on forward otherwise the transaction never stops
		cursor_wait();
		wc.render.getRefreshControllerById(controllerId).url = resultPageURL;
		wc.render.updateContext(contextId, {workAreaMode:workAreaModeValue});
	},
	
	loadPupilList:function(workAreaModeValue, resultPageURL, classId, orderItemId)
	{

	///////////////////////////////////////////////////////////////////
	// summary: This function loads the content from the view for a given URL.
	// Description: This function will take the "resultPageURL" as input attribute, 
	// and will sets the corresponding view content to the "RefreshArea".
	//////////////////////////////////////////////////////////////////			
	//cursor_wait();
	this.orderItemId = orderItemId;
	
	//as the classId value is of the form classId|className, split it to get an array
	var array = classId.split( "|" );

	wc.render.getRefreshControllerById("BasketPupilDisplay_Controller_" + orderItemId).url = resultPageURL+"&classId="+array[0];

	wc.render.updateContext("BasketPagePupilDisplay_Context_" +orderItemId, {workAreaMode:workAreaModeValue});
	
	},
	
	updateOrderCommentNote:function( orderItemId )
	{
		this.orderItemId = orderItemId;
		var commentId = "comment_" + orderItemId;
		var comment = document.getElementById(commentId).value;
		//add the notes prefix. This is just in case in the future we need to distinguish
		//between notes or a student.
		comment = "PFNOTES: " + comment;
		
		this.updateOrderComment( orderItemId, comment );
	},
	
	submitReview: function (form)
	{
		removeSingleErrorMessage("foreName");
		removeSingleErrorMessage("email");
		removeSingleErrorMessage("reviewtitle");
		
		if (form.foreName != null && form.foreName.value.length < 1)
		{
			setErrorMessage("foreName", Common.errorMessages["REQUIRED_FULL_NAME"]);
			form.foreName.focus();
			setError(true);
		}
		if (form.email != null && form.email.value.length < 1)
		{
			setErrorMessage("email", Common.errorMessages["VALID_EMAIL"]);
			form.email.focus();
			setError(true);
		}
		else
		{
			if(!(checkEmail(form.email.value)))
			{
				setErrorMessage("email", Common.errorMessages["INVALIDEMAILFORMAT"]);
				form.email.focus();
				setError(true);
			}
		}
		if (form.reviewtitle != null && form.reviewtitle.value.length < 1)
		{
			setErrorMessage("reviewtitle", Common.errorMessages["REQUIRED_REVIEW_TITLE"]);
			form.reviewtitle.focus();
			setError(true);
		}
		
		if (!getError() && !getBusy())
		{
			setBusy(true);
			cursor_wait();
			wc.service.getServiceById("AJAXManageBookReview").formId = form.name;
			wc.service.invoke("AJAXManageBookReview");
		}
	},
	
	sendToAFriend: function(form)
	{
		//Remove all errors from the form
		removeErrorMessages("sendToFriend");
		
		//Check for errors before submitting
		if (form.fromname != null && form.fromname.value.length < 1)
		{
			setErrorMessage("fromname", Common.errorMessages["REQUIRED_FULL_NAME"]);
			form.fromname.focus();
			setError(true);
		}
		if (form.toname != null && form.toname.value.length < 1)
		{
			setErrorMessage("toname", Common.errorMessages["REQUIRED_FRIENDS_NAME"]);
			form.toname.focus();
			setError(true);
		}
		if (form.fromemail != null && form.fromemail.value.length < 1)
		{
			setErrorMessage("fromemail", Common.errorMessages["REQUIRED_EMAIL"]);
			form.fromemail.focus();
			setError(true);
		}
		else
		{
			if(!(checkEmail(form.fromemail.value)))
			{
				setErrorMessage("fromemail", Common.errorMessages["INVALIDEMAILFORMAT"]);
				form.fromemail.focus();
				setError(true);
			}
		}
		if (form.toemail != null && form.toemail.value.length < 1)
		{
			setErrorMessage("toemail", Common.errorMessages["REQUIRED_FRIENDS_EMAIL"]);
			form.toemail.focus();
			setError(true);
		}
		else
		{
			if(!(checkEmail(form.toemail.value)))
			{
				setErrorMessage("toemail", Common.errorMessages["INVALIDEMAILFORMAT"]);
				form.toemail.focus();
				setError(true);
			}
		}
		
		var encodedFromName = form.fromname.value;
		var encodedToName = form.toname.value;
		var encodedEmailMessage = form.emailMessage.value;
		var encodedOurPrice = form.ourPrice.value;
		var encodedRRP = form.rrp.value;
		var encodedSave = form.save.value;
		var encodedTitle = form.title.value;
		var encodedAuthor = form.author.value;
		var encodedURLInEmail = form.urlInEmail.value;
		//var shortDesc = form.description.value;
			
		//need to encode in case the customer puts any weird characters in (£, $ etc)
		encodedFromName = encodeURIComponent(encodedFromName);
		encodedToName = encodeURIComponent(encodedToName);
		encodedEmailMessage = encodeURIComponent(encodedEmailMessage);
		encodedOurPrice = encodeURIComponent(encodedOurPrice);
		encodedRRP = encodeURIComponent(encodedRRP);
		encodedSave = encodeURIComponent(encodedSave);
		encodedTitle = encodeURIComponent(encodedTitle);
		encodedAuthor = encodeURIComponent(encodedAuthor);		
		encodedURLInEmail = encodeURIComponent(encodedURLInEmail);
		//shortDesc = encodeURIComponent(shortDesc);
		
		form.fromname.value = encodedFromName;
		form.toname.value = encodedToName;
		form.emailMessage.value = encodedEmailMessage;
		form.ourPrice.value = encodedOurPrice;
		form.rrp.value = encodedRRP;
		form.save.value = encodedSave;
		form.title.value = encodedTitle;
		form.author.value = encodedAuthor;
		form.urlInEmail.value = encodedURLInEmail;
		//form.description.value = shortDesc;
		
		if (!getError() && !getBusy())
		{
			setBusy(true);
			cursor_wait();
			//alert("form sent");
			wc.service.getServiceById("AJAXItemInfoNotification").formId = form.name;
			wc.service.invoke("AJAXItemInfoNotification");
		}
	},
	
	updateParamObject:function(params, key, value, toArray, index){
		// summary		: This function updates the given params object with Key value pair.
		// description	: This function updates the given params object with Key value pair.
		//				  If the toArray value is true, It creates an Array for duplicate entries.
		//				  else, It overwrites the old value.
		//				  It is useful while making a service call which excepts few paramters of type array
		// params		: JavaScript Object
		//				  It could be a JavaScript Object or JavaScript Array. JavaScript treats Array as Object only.
		// key			: String
		// value		: String
		// toArray		: Boolean
		//				  If true, creates an Array for duplicate entries
		//				  If false, does not creat an Array for duplicate entries. It overwrites the old value.
		// assumptions	: None.
		// dojo API		: None.
		// returns		: A JavaScript Object having key - value pair.
	   if(params == null){
		   params = [];
	   }

	   if(params[key] != null && toArray)
	   {
			if(dojo.lang.isArrayLike(params[key]))
			{
				//3rd time onwards
			    if(index != null && index != "")
				{
					//overwrite the old value at specified index
				     params[key][index] = value;
				}
				else
				{
				    params[key].push(value);
			     }
		    }
			else
			{
			     //2nd time
			     var tmpValue = params[key];
			     params[key] = [];
			     params[key].push(tmpValue);
			     params[key].push(value);
		    }
	   }
	   else
	   {
			//1st time
		   if(index != null && index != "" && index != -1)
		   {
		      //overwrite the old value at specified index
		      params[key+"_"+index] = value;
		   }
		   else if(index == -1)
		   {
		      var i = 1;
		      while(params[key + "_" + i] != null)
			  {
			       i++;
		      }
		      params[key + "_" + i] = value;
		   }
		   else
		   {
		      params[key] = value;
		    }
	   }
	   return params;
	 },

	 setPupilNameForSubmit:function( form, orderItemId )
	 {
	 	this.orderItemId = orderItemId;
	 	var selectBox = document.getElementById("pupilList_" + orderItemId );
	 	
	 	if( selectBox != null )
	 	{
	 		var selectedIndex  = selectBox.selectedIndex;
	 		if (selectedIndex == -1 )
	 		{
	 			alert("Please select a pupil");
	 			return;
	 		}
	 		var commentField   = document.getElementById("comment_" + orderItemId);
	 		commentField.value = selectBox.options[selectedIndex].value;
	 		
	 		//this.updateShopCart( form ); 
	 		this.updateOrderComment( orderItemId, commentField.value );
	 	}
	 },

	 updateShopCart:function( form, preOrder, availableInventory, existingQuantity )
	 {
		var newQuantity = parseInt(form.updateQuantity.value);
		var updateQuantity = parseInt(existingQuantity) + newQuantity;
		form.quantity.value = updateQuantity;
		
		if( parseInt(availableInventory) < updateQuantity && !preOrder)
		{
			alert('This item is not available in the quantity you have requested. We only have ' + availableInventory + ' in stock');
			form.quantity.value = availableInventory;
		}

		if (preOrder)
		{
			alert("This title is due into the warehouse soon, but please be aware it may delay your order");
		}
		
		if (!getBusy())
		{
			setBusy(true);
			cursor_wait();
			wc.service.getServiceById("AjaxUpdateOrderItem").formId = form.name;
			wc.service.invoke("AjaxUpdateOrderItem");
		}
	},
	addToShopCart:function( form, preOrder, availableInventory )
	 {
		var newQuantity = form.quantity.value = parseInt(form.updateQuantity.value);
		if( parseInt(availableInventory) < newQuantity && !preOrder)
		{
			alert('This item is not available in the quantity you have requested. We only have ' + availableInventory + ' in stock');
			form.quantity.value = availableInventory;
		}

		//updateBasketExtraURLParams(form);
		
		if (preOrder )
		{
			alert("This title is due into the warehouse soon, but please be aware it may delay your order");
		}
		
		if (!getBusy())
		{
			setBusy(true);
			cursor_wait();
			wc.service.getServiceById("AjaxAddOrderItem").formId = form.name;
			wc.service.invoke("AjaxAddOrderItem");
		}
	},
	
	addPBItemToShopCart:function( form, preOrder, availableInventory, existingQuantity )
	{
		
		form.quantity.value = existingQuantity + parseInt(form.updateQuantity.value);
		var newQuantity = parseInt(form.quantity.value);

		if( parseInt(availableInventory) < newQuantity && !preOrder)
		{
			alert('This item is not available in the quantity you have requested. We only have ' + availableInventory + ' in stock');
			form.quantity.value = availableInventory;
		}

		//updateBasketExtraURLParams(form);
		
		if (preOrder )
		{
			alert("This title is due into the warehouse soon, but please be aware it may delay your order");
		}
		
		if (!getBusy())
		{
			setBusy(true);
			cursor_wait();
			if (existingQuantity == 0)
			{
				wc.service.getServiceById("AjaxOrderItemAdd").formId = form.name;
				wc.service.invoke("AjaxOrderItemAdd");
			}
			else
			{
				wc.service.getServiceById("AjaxOrderItemUpdate").formId = form.name;
				wc.service.invoke("AjaxOrderItemUpdate");
			}
		}
	},
	
	deleteFromShopCart: function(orderItmId, catEntryId)
	{
		var params = [];
		params.storeId = this.storeId;
		params.catalogId = this.catalogId;
		params.langId = this.langId;
		params.orderId	= ".";
		params.orderItemId = orderItmId;
		params.catEntryId  = catEntryId;
		
		if (!getBusy())
		{
			setBusy(true);
			cursor_wait();
			wc.service.invoke("AjaxDeleteOrderItem", params);
		}
	},
	
	processBookmarkURL:function(){
		
		// summary: This function is for handling bookmarked urls
		// Description: If there is bookmark information in the url, extract the url after #. 
		//              update context for MyAccountCenterLinkDisplay_Context with the bookmarked url.
		         
		var bookmarkId = location.hash;			
		if(bookmarkId){					        
			bookmarkId = bookmarkId.substring(1, bookmarkId.length);
			
		}   
		
		if(bookmarkId){
		    //to do the best is to make several var for the urls
		    //and then each time add to history, just add in the workareamode
		    //later have a function called sth, it will say if this is the mode, then url = this
		    //if that mode, url = that
		    //and then call load context from url.
		    //the benifit of this is that even this is page is load from bookmark id, 
		    //we still can have the correct mode for it.
		   
	            var indexOfIdentifier = bookmarkId.indexOf("identifier", 0);
	            if ( indexOfIdentifier >= 0) {
		    		var realUrl = bookmarkId.substring(0, indexOfIdentifier - 1);
		    }
		    ShopCart.loadContentFromURL("bookmarkedPage", realUrl);
		}
	},
	
	//to do: add a new function add bookmarkid. move the code for bookmark to here from postrefresh handler.	
	initShopCartHistory:function(sendToFriendUrl, reviewsUrl)
	{
	
		// summary: this function sets the initial state of dojo browser history. 
		// Description: This function sets the initial state of dojo browser history for MyAccountDispay page. 
		// dojo API   : dojo.undo.browser.setInitialState
		// workAreaModeValue: String
		//		a value to uniquely identify an context, which is among the following: 
		//              myAccountMain, personalInformation, addressBook, checkoutProfile, wishList, bookmarkedPage
		// elementId:String
		//             the id of the widget.
		// changeUrl:String
		//             the url used to load new context.

		//Create the urls to be used with the book marking code
		ShopCart.itemDisplayURL = sendToFriendUrl;
		ShopCart.bookReviewsURL = reviewsUrl;
	},
	
	goBack:function(){
	
	// summary: this function belong to HistoryTracking for receiving Back notifications
	// description: this function belong to HistoryTracking for receiving Back notifications	
	// If the user has both refresh areas open then the go back functionality will not work correctly since there
	// is one too many bookmarks. The first back will go back properly, the second will look like it has done nothing,
	// the third will do as the user expected to happen.
			
		ShopCart.loadContentFromURL(this.workAreaModeValue, this.controllerId, this.contextId, this.changeUrl);
		ShopCart.isHistory=true;
		
	},
        
    goForward:function(){
       
	// summary: this function belong to HistoryTracking for receiving forward notifications
	// description:this function belong to HistoryTracking for receiving forward notifications	
	        	
		ShopCart.loadContentFromURL(this.workAreaModeValue, this.controllerId, this.contextId, this.changeUrl, true);
		ShopCart.isHistory=true;
    },
    
    setHistoryTracker:function(refreshArea)
    {
    	switch (refreshArea)
    	{
    		case "ItemDescriptionDisplay":
    			var historyObject = new ShopCart.HistoryTracker("ItemDescriptionDisplay", "ItemDescription_Controller", "ItemDescription_Context", ShopCart.itemDisplayURL);
				break;
			case "BookReviewDisplay":
    			var historyObject = new ShopCart.HistoryTracker("BookReviewDisplay", "BookReview_Controller", "BookReview_Context", ShopCart.bookReviewsURL);
				break;
    	}
    	if (ShopCart.stateSet)
		{
			dojo.undo.browser.addToHistory(historyObject);
		}
		else
		{
			dojo.undo.browser.setInitialState(historyObject);
		}
    	ShopCart.stateSet = true;
    },
	
	HistoryTracker:function(workAreaModeValue, controllerId, contextId, changeUrl)
	{
	
	// summary: History state object for history tracking
	// description:History state object for history tracking
	// workAreaModeValue: String
	//		the html to be displayed
	// elementId: String
	//		the name of the DOM object
	// changeUrl: String
	//		the url for the current state of this page
	
		this.workAreaModeValue = workAreaModeValue;
		this.controllerId = controllerId;
		this.contextId = contextId;
		//TODO: commenting this out breaks FF 1.5. Others? Can't seem to find iframe id/name?
		this.changeUrl =  changeUrl;
	}
}
	ShopCart.HistoryTracker.prototype.back = ShopCart.goBack;
	ShopCart.HistoryTracker.prototype.forward = ShopCart.goForward;