
// prepare the form when the DOM is ready 
jQuery(document).ready(function() {

	    jQuery.getScript("/resources/script/jquery.jframe.js" , function(data, textStatus){
		jQuery.getScript("/resources/script/jquery.taconite.js", function(data, textStatus){				
			jQuery.getScript("/resources/script/jquery.form.js", function(data, textStatus){																																		
				jQuery.getScript("/resources/script/core-custom.js" , function(data, textStatus){				

					loadLanguage(defaultLanguage);

					jQuery.getScript("/resources/script/jquery.cookie.js" , function(data, textStatus){
						loadCart();
						loadLogin();
					});
				
					jQuery.getSytle("/resources/plugin/jgrowl/jquery.jgrowl.css"); 
						jQuery.getScript("/resources/plugin/jgrowl/jquery.jgrowl.js" , function(data, textStatus){ 
						jQuery("body").append("<div id='messages' class='center' style='top:40%'></div>");
					}); 	

				});
				
			
			});
		});
	    });

}); 

 
// before-submit callback 
function beforeSubmitForm(form, formData) {
	var formList =  new Array("formForm","loginForm","userUpdateForm","cartForm","registerForm","passResetForm","passChangeForm","productSearchForm","pageSearchForm");	
	jQuery.each( formList, function(index, item){
		//generic																	
		if( form.name == item ) {
			if( form.name == "productSearchForm" ) {
				var options = { 
					success:	productSearchFormPostSubmitHandler,    	
					url:      "/admin/SubmitHandler?"+jQuery.param(formData),
					clearForm: true
				};			
			}
			else {
				var options = { 
					success:	postSubmitHandler,    	
					url:      "/admin/SubmitHandler?"+jQuery.param(formData),
					clearForm: true
				};
			}
			jQuery(this).ajaxSubmit(options);
		}
	});
	return false;
} 

function initLogin(){
	jQuery.cookie("login", null);
	jQuery.cookie("accountData", null);
	jQuery.cookie("contactData", null);
}

function initCart(){
	jQuery.cookie("cart", null);
	jQuery.taconite("<taconite> " +
									"	<replaceContent select=\"#cart-table tbody\"> " +
									"	<tr>" +
									"	<td></td>" +
									"	<td align=\"right\"></td>" +
									"	<td align=\"right\"></td>" +
									"	<td align=\"right\"></td>" +
									"	<td></td>" +
									"	</tr>" +
									"	</replaceContent> " +  	
									"	<replaceContent select=\"#cart-total\">0.00</replaceContent> " +	
									"	<replaceContent select=\"#cart-sub-total\">0.00</replaceContent> " +  	
									"	<replaceContent select=\"#cart-tax\">0.00</replaceContent> " +    	
									"	<replaceContent select=\"#cart-total\">0.00</replaceContent> " +  	
									" <attr select=\"#tax_cart\" arg1=\"value\" arg2=\"0.00\" />" + 												
									"</taconite>");
	return true;
}

function loadCart(){
	if (jQuery.cookie('cart')!=null) {
		var cart = getCart();
		jQuery.taconite(cart.getXMLCartData());
		jQuery.taconite(cart.getXMLCartMiniData()); 
	}
	return true;
}

function loadLogin(){
	if (jQuery.cookie('login')!=null) {
		var login = getLogin();
		jQuery.taconite( "<taconite>" + login.getAccountData() + "</taconite>" );
		jQuery.taconite( "<taconite>" + login.getContactData() + "</taconite>" );
	}
	return true;
}

function postSubmitHandler(responseText, statusText) {
	jQuery.taconite( responseText );
} 

function formSubmit(form,formAction){
	form.action = formAction;
	form.submit();
}

// utils 
function stringToXML(xmlAstring){
	if (jQuery.browser.msie) {
		var xmlIE = new ActiveXObject("Microsoft.XMLDOM");
		xmlIE.async = false;
		xmlIE.loadXML(xmlAstring);
		return xmlIE;
	}
	else
		return (new DOMParser()).parseFromString(xmlAstring, "text/xml"); 
		
}

jQuery.getSytle = function(styleFile) {
	jQuery.loadStyle(styleFile);
}

jQuery.loadStyle = function(styleFile) {
	var head = document.getElementsByTagName("head")[0];
	var style = document.createElement("link");
	style.setAttribute("rel", "stylesheet");
	style.setAttribute("type", "text/css");
	style.setAttribute("href", styleFile);
	//style.setAttribute("media", "screen");
	head.appendChild(style);
	return true;
}

Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};


function print(div){
	
	jQuery.getScript("/resources/script/jPrint.js" , function(data, textStatus){
	    if (div!=null)
		jQuery('div#'+div).jPrint();
	    else
		jQuery('body').jPrint();

	});
		
}
// utils

function loadJFrame(frame,targetUrl,language){
	jQuery("#"+frame).loadJFrame(targetUrl);
	if (language){
		jQuery.getScript("/resources/script/core-custom.js" , function(data, textStatus){
			loadLanguage(defaultLanguage);
		});	
	}
}

 
function cart(){
	window.location.href = "/extranet/cart.html";
}

function register(){
	initLogin();
	window.location.href = "/extranet/register.html";
}

function access(){
	window.location.href = "/extranet/access.html";
}

function passReset(){
	jQuery("#pass-reset").dialog({
			bgiframe: true,
			resizable: false,
			height:140,
			modal: true,
			overlay: {
				backgroundColor: '#000',
				opacity: 0.5
			}
	});
}

function passChange(){
	jQuery("#pass-change").dialog({
			bgiframe: true,
			resizable: false,
			height:280,
			modal: true,
			overlay: {
				backgroundColor: '#000',
				opacity: 0.5
			}
	});
}

function paymentMethodChange(paymentMethodKey){
	jQuery("#payment-method-detail").loadJFrame("/include/payment-method-" + paymentMethodKey + ".htm");
}

function getLogin(){
	var login = new Login();
	if (jQuery.cookie("login")!=null)
		login.setXMLData(jQuery.cookie("login"));
	return login;
}

function getCart(){
	var cart = new Cart();
	if (jQuery.cookie("cart")!=null)
		cart.setXMLData(jQuery.cookie("cart"));
	return cart;
}

function addProduct(product){
	var cart = getCart();
	cart.addProduct(product);
	jQuery.taconite(cart.getXMLCartMiniData());
	jQuery.cookie("cart",cart.getXMLData(),{path:"/"});
	return false;
}

function updateQuantity(index) {
	var productKey = jQuery("#item_key_"+index).val();
	var quantity = jQuery("#quantity_"+index).val();
	var cart = getCart();
	cart.updateQuantity(productKey,quantity);	
	jQuery.taconite(cart.getXMLCartData());
	jQuery.cookie("cart",cart.getXMLData(),{path:"/"});
	return false;
}
// Cart 

// Objects 
function Login(userKey,userName,fullUserName,accountKey,contactKey,priceType){
	this.userKey = userKey;
	this.getUserKey = function(){
		return this.userKey;
	}
	this.userName = userName;
	this.getUserName = function(){
		return this.userName;
	}
	this.fullUserName = fullUserName;
	this.getFullUserName = function(){
		return this.fullUserName;
	}
	this.accountKey = accountKey;
	this.getAccountKey = function(){
		return this.accountKey;
	}
	this.contactKey = contactKey;
	this.getContactKey = function(){
		return this.contactKey;
	}
	this.priceType = priceType;
	this.getPriceType = function(){
		return this.priceType;
	}
	
	this.setAccountData = function(accountData){
		jQuery.cookie("accountData",accountData,{path:"/"});		
	}
	this.getAccountData = function(){
		if (jQuery.cookie("accountData")!=null)
			return jQuery.cookie("accountData");
	}
	
	this.setContactData = function(contactData){
		jQuery.cookie("contactData",contactData,{path:"/"});
	}
	this.getContactData = function(){
		if (jQuery.cookie("contactData")!=null)
			return jQuery.cookie("contactData");	
	}
	
	this.getXMLData = function(){
		var xmlData =	"<login>" +
									"<userKey>"+this.userKey+"</userKey>"+
									"<userName>"+this.userName+"</userName>"+
									"<fullUserName>"+this.fullUserName+"</fullUserName>"+
									"<accountKey>"+this.accountKey+"</accountKey>"+
									"<contactKey>"+this.contactKey+"</contactKey>"+
									"<priceType>"+this.priceType+"</priceType>"+
									"</login>"; 
		return "<session>"+xmlData+"</session>"; 
	};
	
	this.setXMLData = function(xml){
		var userKey;
		var userName;
		var fullUserName;
		var accountKey;
		var contactKey;
		var priceType;
		xml = stringToXML(xml);
		jQuery(xml).find('login').each(function(){
			userKey = jQuery(this).find('userKey').text();
			userName = jQuery(this).find('userName').text();
			fullUserName = jQuery(this).find('fullUserName').text();
			accountKey = jQuery(this).find('accountKey').text();
			contactKey = jQuery(this).find('quantity').text();
			priceType = jQuery(this).find('priceType').text();
		});
		this.userKey = userKey;
		this.userName = userName;
		this.fullUserName = fullUserName;
		this.accountKey = accountKey;
		this.contactKey = contactKey;
		this.priceType = priceType;
	};
	
}

function Product(productKey,title,url,quantity,price,priceList,account,paypal,extraInformation){	
	this.productKey = productKey;
	this.getProductKey = function(){
		return this.productKey;
	}
	this.title = title;
	this.getTitle = function(){
		return this.title;
	}
	this.url = url;
	this.getUrl = function(){
		return this.url;
	}
	this.price = price;
	this.getPrice = function(){
		if (priceList!=undefined) {
			var objectList = priceList.split("|");
			var login = getLogin();
			if (login.getPriceType()!=undefined) {
				var price=this.price;
				var priceType = login.getPriceType();
				jQuery.each( objectList, function(index, item){
					var object = objectList[index].split(",");
					if (object[1]==priceType)
						price = parseFloat( object[2] );
				});	
				this.price = price;
			}
		}
		return this.price;
	}
 	this.quantity = quantity;
	this.getQuantity = function(){
		return this.quantity;
	}
	this.setQuantity = function(quantity){
		this.quantity = quantity;
	};
	this.priceList = priceList;
	this.getPriceList = function(){
		return this.priceList;
	}
	this.account = account;
	this.getAccount = function(){
		return this.account;
	}
	this.paypal = paypal;
	this.getPaypal = function(){
		return this.paypal;
	}
	this.extraInformation = extraInformation;
	this.getExtraInformation = function(){
		return this.extraInformation;
	}
}

function Cart(){
	this.productList = new Array();
	this.currentIndex = -1;
	this.getCurrentIndex = function(){
		return this.currentIndex;
	}
	this.setCurrentIndex = function(getCurrentIndex){
		this.currentIndex = getCurrentIndex;
	};
	this.getCounter = function(){
		return this.productList.length;
	}	
  this.addProduct = function(product){
		var localIndex = -1;
		jQuery.each( this.productList, function(index, item){
			if ( item.getProductKey() == product.getProductKey() && localIndex < 0 ) {
				item.setQuantity( item.quantity + 1 ); 
				localIndex = index;
			}
		});
		if(localIndex<0) {
			this.productList[this.productList.length] = product;
			this.currentIndex = this.productList.length;
		}
		else
			this.setCurrentIndex(localIndex);
	};
	this.updateQuantity = function(productKey,quantity){
		var localIndex = -1;
		jQuery.each( this.productList, function(index, item){
			if ( item.getProductKey() == productKey && localIndex < 0 ) {
				item.setQuantity( quantity ); 
				localIndex = index;
			}
		});
		if (localIndex>=0 && quantity==0)
			this.productList.remove(localIndex);
	};
	this.getXMLData = function(){
		var xmlData = "";
		jQuery.each( this.productList, function(index, item){
		xmlData += "<product>" +
							 "<productKey>"+item.getProductKey()+"</productKey>"+
							 "<title>"+item.getTitle()+"</title>"+
							 "<url>"+item.getUrl()+"</url>"+
							 "<price>"+item.getPrice()+"</price>"+
							 "<quantity>"+item.getQuantity()+"</quantity>"+
							 "<priceList>"+item.getPriceList()+"</priceList>"+
							 "<account>"+item.getAccount()+"</account>"+
							 "<paypal>"+item.getPaypal()+"</paypal>"+
							 "<extraInformation>"+item.getExtraInformation()+"</extraInformation>"+
							 "</product>"; 
		});
		return "<cart>"+xmlData+"</cart>"; 
	};
	this.setXMLData = function(xml){
		var objectList = new Array();
		xml = stringToXML(xml);
		jQuery(xml).find('product').each(function(){
			product = new Product( parseInt( jQuery(this).find('productKey').text() ), jQuery(this).find('title').text(),jQuery(this).find('url').text(), parseFloat(jQuery(this).find('quantity').text()), parseFloat(jQuery(this).find('price').text()),jQuery(this).find('priceList').text(), jQuery(this).find('account').text(), jQuery(this).find('paypal').text(), jQuery(this).find('extraInformation').text());
			objectList[objectList.length] = product;
		});
		this.productList = objectList;
	};
	this.getXMLCartMiniData = function(){
		var xmlData = "";
		var total = 0;
		jQuery.each( this.productList, function(index, item){
			xmlData += "<tr><td>"+item.getTitle()+"<br/>Cantidad : "+item.getQuantity()+"<br/>Precio : $ "+item.getPrice()+"<hr/></td></tr>";
			total = parseFloat( total ) + parseFloat( item.getPrice() * item.getQuantity() );
		});
		return  "<taconite> " +
						"<replaceContent select=\"#cart-mini tbody\"> " +
						xmlData	 +
						" </replaceContent> " +  	
						"	<replaceContent select=\"#cart-mini-total\">"+parseFloat( total ).toFixed(2) +"</replaceContent> " +
						"</taconite>";
	};
	this.getXMLCartData = function(){
		var xmlData = "";
		var total = 0;

		jQuery('#cart-table > tbody').children( 'tr' ).remove();
		
		jQuery.each( this.productList, function(index, item){
						
			var row = "<tr>";
			
			//Title + Extra Information
			row += 	"<td>" +
							"<input type=\"hidden\" id=\"item_name_"+(index+1)+"\" name=\"item_name_"+(index+1)+"\" value=\""+item.getTitle()+"\"/>"+item.getTitle() +
							( !item.getExtraInformation()==''?"<br/>"+item.getExtraInformation():"" ) + 
							"</td>";
							
			row += 	"<td>"+
							item.getAccount()+
							"</td>";
							
			//Quantity
			row += 	"<td align=\"right\" valign=\"middle\">"+
							"<input id=\"quantity_"+(index+1)+"\" type=\"text\" name=\"quantity_"+(index+1)+"\" value=\""+item.getQuantity()+"\" style=\"text-align:right;width:40px;padding:2px\"/>"+ 
							"<a href=\"#\" onClick=\"updateQuantity("+(index+1)+");\">" +
							"<img src=\"/resources/icons/reload.png\" border=\"0\" hspace=\"4\" vspace=\"4\" width=\"16\" height=\"16\" align=\"absbottom\" />"+			
							"</a> </td>" ;
			//Price
			row += "<td align=\"right\"><input type=\"hidden\" name=\"amount_"+(index+1)+"\" value=\""+item.getPrice()+"\" />"+parseFloat( item.getPrice() ).toFixed(2) + "</td>";
			//Amount
			row  += "<td align=\"right\">"+parseFloat( item.getPrice() * item.getQuantity() ).toFixed(2) +"</td>";
			//Key
			row += "<td><input type=\"hidden\" id=\"item_key_"+(index+1)+"\" name=\"item_key_"+(index+1)+"\" value=\""+item.getProductKey()+"\"/></td>" ;

			row += "</tr>";
			/*
			row += "<tr><td colspan=\"6\"><hr/></td></tr>";
			*/
			jQuery("#cart-table > tbody").append( row );

		  total = parseFloat( total ) + parseFloat( item.getPrice() * item.getQuantity() );
		});


 		jQuery('#cart-table tbody tr:odd').addClass('odd');

		jQuery('#cart-table tbody tr:even').addClass('even');

		return  "<taconite> " +
						"	<replaceContent select=\"#cart-sub-total\">"+parseFloat( total ).toFixed(2) +"</replaceContent> " +  	
						"	<replaceContent select=\"#cart-tax\">"+parseFloat( total * 0.10 ).toFixed(2) +"</replaceContent> " +    	
						"	<replaceContent select=\"#cart-total\">"+parseFloat( total * 1.10 ).toFixed(2) +"</replaceContent> " +  	
						" <attr select=\"#tax_cart\" arg1=\"value\" arg2=\""+parseFloat( total * 0.10 ).toFixed(2) +"\" />" +  						
						"</taconite>";
	};
} 
//Objects