var $j = jQuery.noConflict();

$j(document).ready(function(){
	
	nohide = false;
    // enable transparent overlay on FF/Linux
    $j.blockUI.defaults.applyPlatformOpacityRules = false;
    //clear the default style for message
    $j.blockUI.defaults.css = {};
	
	if (module_enabled()){
		if(!inComparePopUp()){
			update();
		}else{
			comparePopUpLinks();
		}
	}
	
	var eapUrl = gup( 'eapUrl' );
	if (eapUrl != ''){
		new $j.ajax({
		      url: "http://"+eapUrl+"eap/1/",
		      type: "GET",
		      dataType: "html",
		      success: function(msg){
				callbacks(msg, 5);
	     	}
		   });
	}
});

function comparePopUpLinks(){
	if (compare_add_to_cart_enabled()){
		$j('button[onClick*=cart/add]').each(function() {
		    var $t = $j(this);
		    var splitting = $t.attr('onClick').toString().split("'");
		    
		    $t.attr({
		            link : splitting[1],
		            onClick : "",
		        });
		    $t.click(function() {
		    	window.opener.addProduct($t);
		    });
		});
	}
	
	if (wishlist_add_enabled()){
		$j('a[onClick*=wishlist/index/add]').each(function(){
			
		    var $t = $j(this);
		    
		    var splitting = $t.attr('onClick').toString().split("'");
		    
		    $t.removeAttr("href");
		    $t.addClass("addLink");
		    $t.attr({
		            link : splitting[1],
		            onClick : "",
		        });
		    $t.click(function() {
		    	window.opener.Wishlist($t.attr("link"));
		    });
		});
	}
	
	if (compare_delete_enabled()){
		$j('a[onClick*=product_compare/remove/]').each(function(){
			
		    var $t = $j(this);
		    
		    var splitting = $t.attr('onClick').toString().split("'");
		    
		    $t.removeAttr("href");
		    $t.addClass("addLink");
		    $t.attr({
		            link : splitting[1],
		            onClick : "",
		        });
		    $t.click(function() {
		    	window.opener.Compare($t.attr("link"));
		    	refreshComparePopUp();
		    });
		});
	}
}

function update(){
	
	$j('div.block.block-cart').attr('id', 'cart_sidebar');
	$j('div.block.block-wishlist').attr('id', 'wishlist_sidebar');
	$j('div.block.block-compare').attr('id', 'compare_sidebar');

	if(cart_add_enabled()){
		$j('button[onClick*=cart/add]').each(function() {
		    var $t = $j(this);
		    var splitting = $t.attr('onClick').toString().split("'");
		    $t.attr({
		            link : splitting[1],
		            onClick : "",
		            addType : 1
		        });
		});

		if(options_enabled()){
			$j('button[onClick*=?options=cart]').each(function(){
				if (window.location.pathname.split('/').reverse()[1] != 'cart'){
					var $t = $j(this);

					var id = $t.next().children().children().attr("href").split('/').reverse()[1];
					$t.attr({
			            pid : id,
			            onClick : "",
			            addType : 1.5 
			        });
				}
			});
		}

		$j('button[onClick=productAddToCartForm.submit()]').each(function(){
			var $t = $j(this);
			if( $j("#product-options-wrapper").length > 0){
				if(options_enabled()){
					var _pid = $j('fieldset.no-display input[type=hidden],input[name=product],input[value]').attr('value');
					var i = 1;
//					while(!IsNumeric(_pid)){
//						_pid = $j('fieldset.no-display input[type=hidden],input[name=product],input[value]:eq(i)').attr('value');}
					    $t.attr({
					    pid : _pid,
					    onClick : "",
					    addType : 2
					});
				}
			}else{
				var _pid = $j('fieldset.no-display input[type=hidden],input[name=product],input[value]').attr('value');
				var i = 1;
				while(!IsNumeric(_pid)){
					_pid = $j('fieldset.no-display input[type=hidden],input[name=product],input[value]:eq(i)').attr('value');}
			    $t.attr({
		            pid : _pid,
		            onClick : "",
		            addType : 1,
		            link : $j("#easyajaxproduct_linkurl").attr("value")+"checkout/cart/add/product/"+_pid+"/",
		        });
			}
		});
	}

	if(compare_add_enabled()){
		$j('a[href*=catalog/product_compare/add]').each(function(){
		    var $t = $j(this);
		    link = $t.attr("href");
		    $t.removeAttr("href");
		    $t.addClass("addLink");
		    $t.attr({
		        link : link,
		        onClick : ''
		    });
		    $t.click(function(){
		    	Compare($t.attr("link"));
		    });
		});
	}
	
	if(wishlist_add_enabled()){
		$j('a[href*=wishlist/index/add]').each(function(){
		    var $t = $j(this);
		    link = $t.attr("href");
		    $t.removeAttr("href");
		    $t.addClass("addLink");
		    $t.attr({
		        link : link,
		    });
		    $t.click(function(){
		    	Wishlist($t.attr("link"));
		    });
		});
	}
	
	$j('button[addType=2]').click(function(){
		if(submitFormWithOptions(false) != 1){
			showAll();
			showPopUpLoading();
		
			cart_opacity_less();
		}
    });

	$j('button[addType=1]').click(function(){
		addProduct($j(this), false);
    });
	$j('button[addType=1.5]').click(function(){
		addProduct($j(this), true);
    });
	$j("#ajax_continue_shopping").click(function(){
		hideAll();
	});
	$j("#ajax_checkout").click(function(){
		window.setLocation($j("#ajax_checkout").attr("dest"));
	});
	
	refreshWishlistLinks();
	refreshCompareLinks();
}

function refreshCompareLinks(){
	if(compare_delete_enabled() || compare_add_to_cart_enabled()){
		$j('button[onclick*=popWin]').each(function(){
		    var $t = $j(this);
		    var link = $t.attr("onClick");
		    res = link.replace('/\'','/eap/1/\'');
		    
		    $t.attr({
		        onClick : res
		    });

		});
		
		if(compare_delete_enabled()){
			$j('a[href*=catalog/product_compare/remove]').each(function(){
			    var $t = $j(this);
			    link = $t.attr("href");
			    $t.removeAttr("href");
			    $t.addClass("addLink");
			    
			    $t.children("img").removeAttr("onclick");
			    
			    $t.attr({
			        link : link,
			        onclick : ''
			    });
			    $t.click(function(){
			    	Compare($t.attr("link"));
			    });
			});
		}
		if(compare_clear_all_enabled()){
			$j('a[href*=catalog/product_compare/clear]').each(function(){
			    var $t = $j(this);
			    link = $t.attr("href");
			    $t.removeAttr("href");
			    $t.addClass("addLink");
		    
			    $t.attr({
			        link : link,
			        onclick : ''
			    });
			    $t.click(function(){
			    	Compare($t.attr("link"));
			    });
			});
		}
	}
}
function refreshWishlistLinks(){
	if(wishlist_delete_enabled()){
		$j('#wishlist_sidebar a[href*=wishlist/index/remove]').each(function(){
		    var $t = $j(this);
		    link = $t.attr("href");
		    $t.removeAttr("href");
		    $t.addClass("addLink");
		    $t.attr({
		    	onClick : "",
	            link : link,
		    });
		    
		    $t.click(function(){
		    	WishlistRemove($t.attr("link"));
		    });
		});
	}
	
	if(wishlist_add_to_cart_enabled()){
		$j('#wishlist_sidebar a[href*=wishlist/index/cart]').each(function(){
		    var $t = $j(this);
		    link = $t.attr("href");
		    $t.removeAttr("href");
		    $t.addClass("addLink");
		    $t.attr({
		    	link : link,
		        addType : 3,
		    });
		});
		$j('a[addType=3]').click(function(){
	    	addWishlistProduct($j(this).attr("link"));
	    });
	}
}

function refreshWishList(msg){
	reponse = msg.replace('<div class="block block-wishlist">', '');
	var sidebar = $j("#wishlist_sidebar");
	sidebar.html(reponse);
	wishlist_opacity_more();
}

function refreshCompare(msg){
	reponse = msg.replace('<div class="block block-compare">', '');
	var sidebar = $j("#compare_sidebar");
	sidebar.html(reponse);
	compare_opacity_more();
}

function refreshComparePopUp(){
	window.location = $j("#easyajaxproduct_linkurl").attr("value")+"catalog/product_compare/index/";
}


function callbacks(xhr, id)
{
	if (xhr.substring(0,5) == "error"){
		var reponse = xhr.replace('error', '');
		showError(reponse);
	}else{
		
	 	if (id == 1 || id == 6){// add
	 		hidePopUpLoading();
	
	 		if (xhr.substring(0,7) == "options"){
                $j.unblockUI({
                    onUnblock: function(){
                        showAllNormal();
                        var reponse = xhr.replace('options', '<input type="hidden" id="callbackId" value="'+id+'" />');
                        reponse = reponse.replace('<div class="product-info-box"></div>', '');
                        $j("#ajaxaddtocart_popup_options_in").html(reponse);
                        showPopUpOptions();
                        $j("#ajaxaddtocart").css("max-height", height());
                        $j("#ajaxaddtocart").css("top", center("ajaxaddtocart_popup_options"));
                    }
                });
	 		}
	 		else if (xhr.substring(0,5) == "super"){
                $j.unblockUI({
                    onUnblock: function(){
                        showAllNormal();
                        showPopUpRedirecting();
                        var reponse = xhr.replace('super', '');
                        window.location = reponse;
                    }
                });
	 		}
	 		else if (xhr.substring(0,12) == "configurable"){
                $j.unblockUI({
                    onUnblock: function(){
                        showAllNormal();
                        var reponse = xhr.replace('configurable', '<input type="hidden" id="callbackId" value="'+id+'" />');
                        reponse = reponse.replace('<div class="product-info-box"></div>', '');
                        $j("#ajaxaddtocart_popup_options_in").html(reponse);
                        showPopUpOptions();
                        $j("#ajaxaddtocart").css("max-height", height());
                        $j("#ajaxaddtocart").css("top", center("ajaxaddtocart_popup_options"));
                    }
                });
	 		}
	 		else if (xhr.substring(0,7) == "grouped"){
                $j.unblockUI({
                    onUnblock: function(){
                        showAllNormal();
                        var reponse = xhr.replace('grouped', '<input type="hidden" id="callbackId" value="'+id+'" />');
                        reponse = reponse.replace('<div class="product-info-box"></div>', '');
                        $j("#ajaxaddtocart_popup_options_in").html(reponse);
                        showPopUpOptions();
                        $j("#ajaxaddtocart").css("max-height", height());
                        $j("#ajaxaddtocart").css("top", center("ajaxaddtocart_popup_options"));
                    }
                });
	 		}
	 		else if (xhr.substring(0,6) == "bundle"){
                $j.unblockUI({
                    onUnblock: function(){
                        showAllNormal();
                        var reponse = xhr.replace('bundle', '<input type="hidden" id="callbackId" value="'+id+'" />');
                        reponse = reponse.replace('<div class="product-info-box"></div>', '');
                        $j("#ajaxaddtocart_popup_options_in").html(reponse);
                        showPopUpOptions();
                        $j("#ajaxaddtocart").css("max-height", height());
                        $j("#ajaxaddtocart").css("top", center("ajaxaddtocart_popup_options"));
                    }
                });
	 		}
	 		else{
                $j.unblockUI({
                    onUnblock: function(){
                        showPopUp();

                        if(id == 6 || $j("#callbackId").attr('value') == 6){

                            split = xhr.split('##ajax_splitting##');
                            xhr = split[1];
                            reponse = split[0].replace('<div class="block block-wishlist">', '');

                            var sidebar = $j("#wishlist_sidebar");
                            sidebar.html(reponse);
                            wishlist_opacity_more();
                            refreshWishlistLinks();
                        }

                        reponse = xhr.replace('<div id="cart_sidebar" class="block block-cart">', '');

                        var sidebar = $j("#cart_sidebar");
                        sidebar.html(reponse);
                        cart_opacity_more();
                        truncateOptions();
                    }
                });
            }
	   }else{
		   nohide = false;
		   if (id == 3){// remove
			   reponse = xhr.replace('<div id="cart_sidebar" class="block block-cart">', '');
		
		      var sidebar = $j("#cart_sidebar");
		      sidebar.html(reponse);
		
		      cart_opacity_more();
		      
		      
		   }else if (id == 4){// cancel last delete & navigation
			   reponse = xhr.replace('<div id="cart_sidebar" class="block block-cart">', '');
		   		var sidebar = $j("#cart_sidebar");
				sidebar.html(reponse);
		
				cart_opacity_more();
		      
		   }else if (id == 5){// add to wishlist
                $j.unblockUI({
                    onUnblock: function(){
                       hidePopUpLoading();
                       var reponse = xhr.split('login-form');
                       if (reponse.length > 1){// customer not logged in
                           showLoginPopUp();
                       }else{// customer logged in
                           hideAll();
                           refreshWishList(xhr);
                       }
                    }
                });
		   }else if (id == 7){// remove from wishlist
                $j.unblockUI({
                    onUnblock: function(){
                       hidePopUpLoading();
                       hideAll();
                       refreshWishList(xhr);
                    }
                });
		   }else if (id == 8){// Compare
                $j.unblockUI({
                    onUnblock: function(){
                       hidePopUpLoading();
                       hideAll();
                       refreshCompare(xhr);
                    }
                });
		   }else if (id == 9){// Compare Pop Up
                $j.unblockUI({
                    onUnblock: function(){
                       refreshComparePopUp(xhr);
                    }
                });
		   }
	   }
	   $j(".imagezoom").hide();
	}
}

function addProduct(x, options){
	showAll();
	showPopUpLoading();
	
	cart_opacity_less();
	
	if(options){
		var link = $j("#easyajaxproduct_linkurl").attr("value")+"checkout/cart/add/options/1/product/"+x.attr("pid")+"/";
	}else{
	 	var link = x.attr("link");
		var qty = $j("#qty").attr("value");
		if (!IsNumeric(qty)){
			qty = 1;}
	}
	
	new $j.ajax({
      url: link+"qty/"+qty+"/eap/1/",
      type: "GET",
      dataType: "html",
      success: function(msg){
         callbacks(msg, 1);
      }
   });
}

function addWishlistProduct(x){
	showAll();
	showPopUpLoading();

	cart_opacity_less();
	wishlist_opacity_less();

	new $j.ajax({
      url: x+"eap/1/",
      type: "GET",
      dataType: "html",
      success: function(msg){
         callbacks(msg, 6);
      }
   });
}

function submitFormWithOptions(fromwishlist){
    var productAddToCartForm = new VarienForm('product_addtocart_form');
        if (productAddToCartForm.validator.validate()) {
        	hidePopUpOptions();
        	showPopUpLoading();
        	
        	cart_opacity_less();
        	
        	var ncallback = 1;
        	if (fromwishlist == 1){
        		ncallback = 6;
        	}
    		var qty = $j("#qty").value;
    		if (!IsNumeric(qty)){
    			qty = 1;}
        	new $j.ajax({
        	      url: $j("#easyajaxproduct_linkurl").attr("value")+"checkout/cart/add/qty/"+qty+"/params/1/eap/1/fromwishlist/"+fromwishlist+"/?"+$j('#product_addtocart_form').serialize(),
        	      type: "GET",
        	      dataType: "html",
        	      success: function(msg){
        	         callbacks(msg, ncallback);
        	      }
        	   });
        }else{
		return 1;
	}
}

function Wishlist(x){
	showAll();
	showPopUpLoading();
	
	wishlist_opacity_less();

	new $j.ajax({
      url: x+"eap/1/",
      type: "GET",
      dataType: "html",
      success: function(msg){
        callbacks(msg, 5);
     }
   });
}

function WishlistRemove(url){
	showAll();
	showPopUpLoading();
	
	wishlist_opacity_less();

	new $j.ajax({
      url: url+"eap/1/",
      type: "GET",
      dataType: "html",
      success: function(msg){
        callbacks(msg, 7);
     }
   });
}

function Compare(url){
	showAll();
	showPopUpLoading();
	
	compare_opacity_less();

	new $j.ajax({
      url: url+"eap/1/",
      type: "GET",
      dataType: "html",
      success: function(msg){
        callbacks(msg, 8);
     }
   });
}

