// General Functions
var request_uri;
var checkout_cart_url;
var updateLinkUrl;
var ok_button_label;
var cancel_button_label;
var delete_confirm_text;
var enable_success_message;
var button_bg_color
var button_border_color;
var button_font_color;

function setAllTheUrls(php_request_uri, php_checkout_cart_url, php_updateLinkUrl, php_homeUrl, php_ok_button_label, php_cancel_button_label, php_delete_confirm_text, php_enable_success_message, php_button_bg_color, php_button_border_color, php_button_font_color){
	request_uri = php_request_uri;
	checkout_cart_url = php_checkout_cart_url;
	updateLinkUrl = php_updateLinkUrl;	
	home_url = php_homeUrl;
	ok_button_label = php_ok_button_label;
	cancel_button_label = php_cancel_button_label;
	delete_confirm_text = php_delete_confirm_text;
	enable_success_message = php_enable_success_message;
	button_bg_color = php_button_bg_color;
	button_border_color = php_button_border_color;
	button_font_color = php_button_font_color;
}

function setLocation(url){

	strurl = url;
	var match1 = /options=cart/.test(strurl);
	var match2 = /checkout\/onepage/.test(strurl);
	var match3 = /limit\=\w+/.test(strurl);
	var match4 = /order\=\w+\&dir\=\w+/.test(strurl);
	var match5 = /dir\=\w+\&order\=\w+/.test(strurl);
	
	var checkForCartAddToCart = /in_cart\/1/.test(strurl)
	if(checkForCartAddToCart){
		return inCartAddToCart(strurl);
	}
	
	var ajax = true;
	if(match1){
		ajax = false;
	}
	if(match2){
		ajax = false;
	}
	if(match3){
		ajax = false;
	}
	if(match4){
		ajax = false;
	}
	if(match5){
		ajax = false;
	}
	
	if(strurl==home_url){
		ajax = false;
	}
	
	if(ajax){
		Element.show('loading-mask');  
		
		new Ajax.Request(url, {
          onSuccess: function(transport) {
			  Element.hide('loading-mask');  
			  var json = transport.responseText.evalJSON();
			  
			  if(json.r=="failure"){
				if(json.redirect_url==null){
					showErrorMessage(json.messages);
				}else{
					window.location = json.redirect_url;
				}
			  }else{
				if(json.from=="wishlist"){
					showDialog(json.message);
					updateTopCartLink(json.topCartText);
					updateTopWishText(json.topWishText);
					updateWishlistBlock(json.wishlist);
					updateSideBarCart(json.cart);
				}else{
					showDialog(json.message);
					updateTopCartLink(json.topCartText);
					updateSideBarCart(json.cart);
					findAndCleanUpDeleteUrls();
				}
			}
          }, method: "get"
		});
	}else{
		window.location.href = url;
	}
	
}

function setPLocation(url, setFocus){
	var patt1=new RegExp("/checkout/cart/add/product/");
	if(patt1.test(url)){
		Element.show('loading-mask');  
		new Ajax.Request(url, {
          onSuccess: function(transport) {
			  Element.hide('loading-mask');  
			  var json = transport.responseText.evalJSON();
			  
			  if(json.r=="failure"){
				window.blur();
				window.opener.location.href = json.redirect_url;
			  }else{
				showDialog(json.message, 'compare_page');
				window.opener.location.reload();
			}
          }, method: "get"
		});
	}else{
		if( setFocus ) {
			window.opener.focus();
		}
		window.opener.location.href = url;
	}
}

function inCartAddToCart(strurl){
	Element.show('loading-mask'); 
	new Ajax.Request(strurl, {
	  onSuccess: function(transport) {
		  Element.hide('loading-mask');  
		  
		  
			var json = transport.responseText.evalJSON();
					
			if(json.r=="failure"){
				if(json.redirect_url==null){
					showErrorMessage(json.messages);
				}else{
					window.location = json.redirect_url;
				}
			}else{
				updateTopCartLink(json.topCartText);
				updateBigCart(json.cart);
				findAndCleanUpDeleteUrls();
			}	  
			
	  }, method: "get"
	});
}

function findAndCleanUpDeleteUrls(){
	var patt1=new RegExp("/checkout/cart/delete/");
	for(i=0;i<document.links.length;i++){
		if(patt1.test(document.links[i])){
			url_with_random_chars = document.links[i].href;
			clean_url = url_with_random_chars.replace(/\/uenc\/\w*\W*/i, "/")
			document.links[i].id = clean_url;
			var patt2=new RegExp("/checkout/cart/");
			if(patt2.test(request_uri)){
				document.links[i].href = "javascript:ajaxDeleteCartProduct('"+document.links[i].id+"')";		
			}else{
				document.links[i].href = "javascript:ajaxDeleteProduct('"+document.links[i].id+"')";		
			}
			
			document.links[i].onclick = "";
					
		}
	}
	
	// also update all add to cart href links
	updateAllHrefLinksToUseSetLocation();
}


// Product Detail Page Functions
var productAddToCartForm = new VarienForm('product_addtocart_form');
productAddToCartForm.submit = function(){
		if (this.validator.validate()) {
			Element.show('loading-mask');  
			
			// do the same with a callback:
			$('product_addtocart_form').request({
				onComplete: function(transport){ 
					Element.hide('loading-mask');
					
					var json = transport.responseText.evalJSON();
					
					if(json.r=="failure"){
						if(json.redirect_url==null){
							showErrorMessage(json.messages);
						}else{
							window.location = json.redirect_url;
						}
					}else{
					
						showDialog(json.message);
						updateTopCartLink(json.topCartText);
						updateSideBarCart(json.cart);
						findAndCleanUpDeleteUrls();
					}
				}
			})

		}
}.bind(productAddToCartForm);


// Cart Page Functions
function ajaxDeleteCartProduct(url){	

	if(makeDeleteConfirm()){
		Element.show('loading-mask');  
		url += "request_from/checkout/";
		
		new Ajax.Request(url, {  
		method: 'get',
		onComplete: function(transport) {  
		
			Element.hide('loading-mask');
		
			// option 1 start
			var json = transport.responseText.evalJSON();
					
			if(json.r=="failure"){
				window.location = json.redirect_url;
			}else{
			
				updateTopCartLink(json.topCartText);
				updateBigCart(json.cart);
				findAndCleanUpDeleteUrls();
			}
			// option 1 end
		}
			
		});
	}
}

// Side Bar Functions

function ajaxDeleteProduct(url){
	if(makeDeleteConfirm()){
		Element.show('loading-mask');  
		new Ajax.Request(url, {  
		method: 'get',  
		onComplete: function(transport) {  
		Element.hide('loading-mask');  
		var json = transport.responseText.evalJSON();
		updateSideBarCart(json.cart);
		updateTopCartLink(json.topCartText);
		findAndCleanUpDeleteUrls();
		}  
		});  
	}
}

function updateSideBarCart(jsonCart){
	var divs = document.getElementsByTagName('div');
	for (var i = 0; i < divs.length; i++) {
		var div = divs[i];
		if(div.className=="box base-mini mini-cart"){
			div.innerHTML = jsonCart;
			Effect.BlindDown(div);
			break;
		}
	}
}

function makeDeleteConfirm(){
	if(window.confirm(delete_confirm_text)){
		return true;
	}
	return false;
}

function updateTopCartLink(topCartText){
	// document.getElementById('top_cart_link_strong').innerHTML = topCartText;
	// return;
	var divS = document.getElementsByTagName('div');
	for (var i = 0; i < divS.length; i++) {
		var div = divS[i];
		if(div.className=="itemscart"){
			div.innerHTML = topCartText;
			//a.title = topCartText;
			return;
		}
	}
}

function updateTopWishText(topWishText){
	var aS = document.getElementsByTagName('a');
	for (var i = 0; i < aS.length; i++) {
		var a = aS[i];
		if(a.className=="top-link-wishlist"){
			a.innerHTML = topWishText;
			a.title = topWishText;
			return;
		}
	}
}

function showDialog(jsonMessage, from){
	if(enable_success_message=="1"){
	
		// inputButtons = "<br/><br/><input type='image' name='finish_and_checkout' id='finish_and_checkout' src='"+skin_url+"images/button_checkout.png'/><br/><br/><input type='image' name='continue_shopping' id='continue_shopping' src='"+skin_url+"images/button_keepshopping.png'/>";
		
		// scriptCode = "<script type='text/javascript'>";
		// if(from=='compare_page'){	
			// scriptCode += "$('finish_and_checkout').observe('click', function(){ Effect.DropOut('after-loading-success-message'); window.opener.location.href = checkout_cart_url; window.opener.focus(); });";
		// }else{
			// scriptCode += "$('finish_and_checkout').observe('click', function(){location.href = checkout_cart_url;});";
		// }
		// scriptCode += "$('continue_shopping').observe('click', function(){Effect.DropOut('after-loading-success-message')});"
		
		// scriptCode += "</script>";
	
		// Element.update('success-message-container', jsonMessage+inputButtons+scriptCode);
		// Element.show('after-loading-success-message');
		inputButtons = "<br/><br/><input type='button' name='finish_and_checkout' id='finish_and_checkout' value='"+ok_button_label+"' style='background:"+button_bg_color+" none repeat scroll 0 0; border:1px solid "+button_border_color+"; color:"+button_font_color+"; cursor:pointer; font-family:arial,sans-serif !important; font-size:12px !important; font-size-adjust:none !important; font-stretch:normal !important; font-style:normal !important; font-variant:normal !important; font-weight:bold !important; line-height:normal !important; overflow:visible; padding:1px 8px; text-align:center; vertical-align:middle;' /><br/><br/><input type='button' name='continue_shopping' id='continue_shopping' value='"+cancel_button_label+"' style='background:"+button_bg_color+" none repeat scroll 0 0; border:1px solid "+button_border_color+"; color:"+button_font_color+"; cursor:pointer; font-family:arial,sans-serif !important; font-size:12px !important; font-size-adjust:none !important; font-stretch:normal !important; font-style:normal !important; font-variant:normal !important; font-weight:bold !important; line-height:normal !important; overflow:visible; padding:1px 8px; text-align:center; vertical-align:middle;' />";
		
		scriptCode = "<script type='text/javascript'>";
		if(from=='compare_page'){	
			scriptCode += "$('finish_and_checkout').observe('click', function(){ Effect.DropOut('after-loading-success-message'); window.opener.location.href = checkout_cart_url; window.opener.focus(); });";
		}else{
			scriptCode += "$('finish_and_checkout').observe('click', function(){location.href = checkout_cart_url;});";
		}
		scriptCode += "$('continue_shopping').observe('click', function(){Effect.DropOut('after-loading-success-message')});"
		
		scriptCode += "</script>";
	
		Element.update('success-message-container', jsonMessage+inputButtons+scriptCode);
		Element.show('after-loading-success-message');
	}
	return;
}

function updateAllHrefLinksToUseSetLocation(){
	var patt1=new RegExp("/checkout/cart/add/");
	for(i=0;i<document.links.length;i++){
		if(patt1.test(document.links[i])){
			url = document.links[i].href;
			document.links[i].href = "javascript:setLocation('"+url+"')";
		}
	}
}

function updateWishlistBlock(jsonWishlist){
	var divs = document.getElementsByTagName('div');
	for (var i = 0; i < divs.length; i++) {
		var div = divs[i];
		if(div.className=="my-account"){
			div.innerHTML = jsonWishlist;
			break;
		}
	}
}

function updateBigCart(jsonCart){
	var divs = document.getElementsByTagName('div');
	document.getElementById('main').innerHTML = jsonCart;
	
	var scripts = jsonCart.extractScripts();
	for(var i=0; i<scripts.length; i++){
		var code = scripts[i].strip().gsub(/var\s+/, '');
		eval(code);
	}
	// for (var i = 0; i < divs.length; i++) {
		// var div = divs[i];
		// if(div.className=="col-main"){
			// div.innerHTML = jsonCart;
			
			// var scripts = jsonCart.extractScripts();
			// for(var i=0; i<scripts.length; i++){
				// var code = scripts[i].strip().gsub(/var\s+/, '');
				// eval(code);
			// }
			
			// break;
		// }
	// }
	return;
}

function showErrorMessage(message){
	Element.update('success-message-container', message);
	Element.show('after-loading-success-message');
}
