/**
 * J2T-DESIGN.
 *
 * @category   J2t
 * @package    J2t_Ajaxcheckout
 * @copyright  Copyright (c) 2003-2009 J2T DESIGN. (http://www.j2t-design.com)
 * @license    GPL
 */
/*
var loadingW = 260;
var loadingH = 50;
var confirmW = 260;
var confirmH = 134;
*/
var inCart = false;

if (window.location.toString().search('/product_compare/') != -1){
	var win = window.opener;
}
else{
	var win = window;
}

if (window.location.toString().search('/checkout/cart/') != -1){
    inCart = true;
}

function setLocation(url){
    if(!inCart && ((url.search('/add') != -1 ) || (url.search('/remove') != -1 ) || url.search('checkout/cart/add') != -1) ){
        sendcart(url, 'url', false);
    }else{
        window.location.href = url;
    }
}


function sendcart(url, type, continuetocheckout){
    showLoading(true, 'Adding to shopping bag..');
    if (type == 'form'){
        url = ($('product_addtocart_form').action).replace('checkout', 'j2tajaxcheckout/index/cart');
        var myAjax = new Ajax.Request(
        url,
        {
            method: 'post',
            postBody: $('product_addtocart_form').serialize(),
            parameters : Form.serialize("product_addtocart_form"),
            onException: function (xhr, e)
            {
                alert('Exception : ' + e);
            },
            onComplete: function (xhr)
            {

                var start3 = xhr.responseText.indexOf('<div class="j2t_ajax_message">')+30;
                var end3 = xhr.responseText.indexOf("<span>j2t_ajax_auto_add</span></div>",start3);
                var return_message = xhr.responseText.substring(start3, end3);

                var start= xhr.responseText.indexOf('<div id="back-ajax-add">')+24;
                var end= xhr.responseText.indexOf("</div>",start);
                $('j2t_ajax_confirm').innerHTML = return_message + xhr.responseText.substring(start,end);
                var start2 = xhr.responseText.indexOf('<div id="cart_content">')+23;
                var end2= xhr.responseText.indexOf("</div>",start2);
                $$('.top-link-cart').each(function (el){
                    el.innerHTML = xhr.responseText.substring(start2,end2);
                });

                var start4 = xhr.responseText.indexOf('<div class="cart_side_ajax">')+28;
                var end4 = xhr.responseText.indexOf("<span>j2t_ajax_auto_add</span></div>",start4);
                
                var start5 = xhr.responseText.indexOf('<div class="cart_side_title_ajax">')+34;
                var end5 = xhr.responseText.indexOf("<span>j2t_ajax_auto_add</span></div>",start5);

                //$$('.mini-cart').each(function (el){
                $$('.mini-products-list').each(function (el){
                    el.replace(xhr.responseText.substring(start4,end4));
                    //new Effect.Opacity(el, { from: 0, to: 1, duration: 1.5 });
                });
                $$('.top-block-cart').each(function (el){
                    el.replace(xhr.responseText.substring(start4,end4));
                    //new Effect.Opacity(el, { from: 0, to: 1, duration: 1.5 });
                });
				$$('.header-cart-title').each(function (el){
                    el.replace(xhr.responseText.substring(start5,end5));
                    //new Effect.Opacity(el, { from: 0, to: 1, duration: 1.5 });
                });
				
                replaceDelUrls();
				/*
                if (ajax_cart_show_popup){
                    showConfirm();
                } else {
                    hideJ2tOverlay();
                }
                */
               if(continuetocheckout){
				    window.location = "/onestepcheckout/";
				    return false;
			   }else{
	               	hideJ2tOverlay();
					jQuery('#cart-content').slideDown("fast").animate({opacity: 1.0}, 2000).fadeOut(2500);
	           }

            }

        });



    } else if (type == 'url'){

        url = url.replace('checkout', 'j2tajaxcheckout/index/cart');
        //alert(url);
        var myAjax = new Ajax.Request(
        url,
        {
            method: 'post',
            postBody: '',
            onException: function (xhr, e)
            {
                alert('Exception : ' + e);
            },
            onComplete: function (xhr)
            {
                //alert(xhr.responseText);
                var start3 = xhr.responseText.indexOf('<div class="j2t_ajax_message">')+30;
                var end3 = xhr.responseText.indexOf("<span>j2t_ajax_auto_add</span></div>",start3);
                var return_message = xhr.responseText.substring(start3, end3);


                var start= xhr.responseText.indexOf('<div id="back-ajax-add">')+24;
                var end= xhr.responseText.indexOf("</div>",start);
                $('j2t_ajax_confirm').innerHTML = return_message + xhr.responseText.substring(start,end);
                var start2 = xhr.responseText.indexOf('<div id="cart_content">')+23;
                var end2= xhr.responseText.indexOf("</div>",start2);
                $$('.top-link-cart').each(function (el){
                    el.innerHTML = xhr.responseText.substring(start2,end2);
                });


                var start4 = xhr.responseText.indexOf('<div class="cart_side_ajax">')+28;
                var end4 = xhr.responseText.indexOf("<span>j2t_ajax_auto_add</span></div>",start4);
 				var start5 = xhr.responseText.indexOf('<div class="cart_side_title_ajax">')+34;
                var end5 = xhr.responseText.indexOf("<span>j2t_ajax_auto_add</span></div>",start5);

                $$('.mini-products-list').each(function (el){
                    el.replace(xhr.responseText.substring(start4,end4));
                    //new Effect.Opacity(el, { from: 0, to: 1, duration: 1.5 });
                });
                $$('.top-block-cart').each(function (el){
                    el.replace(xhr.responseText.substring(start4,end4));
                    //new Effect.Opacity(el, { from: 0, to: 1, duration: 1.5 });
                });
				$$('.header-cart-title').each(function (el){
                    el.replace(xhr.responseText.substring(start5,end5));
                    //new Effect.Opacity(el, { from: 0, to: 1, duration: 1.5 });
                });
                replaceDelUrls();
				/*
                if (ajax_cart_show_popup){
                    showConfirm();
                } else {
                    hideJ2tOverlay();
                }
                */
               if(continuetocheckout){
				    window.location = "/onestepcheckout/";
				    return false;
			   }else{
               	hideJ2tOverlay();
				jQuery('#cart-content').slideDown("fast").animate({opacity: 1.0}, 2000).fadeOut(2500);
	           }

	        }

        });
    }
    
}

function replaceDelUrls(){
    if (!inCart){
        $$('a').each(function(el){
            if(el.href.search('checkout/cart/delete') != -1){
                el.href = 'javascript:cartdelete(\'' + el.href +'\')';
            }
        });
    }
}

function replaceAddUrls(){
    $$('a').each(function(link){
        if(link.href.search('checkout/cart/add') != -1){
            link.href = 'javascript:setLocation(\''+link.href+'\'); void(0);';
        }
    });
}

function cartdelete(url){
    showLoading(true, 'Removing item..');
    url = url.replace('checkout', 'j2tajaxcheckout/index/cart');
    var myAjax = new Ajax.Request(
    url,
    {
        method: 'post',
        postBody: '',
        onException: function (xhr, e)
        {
            alert('Exception : ' + e);
        },
        onComplete: function (xhr)
        {


            var start2 = xhr.responseText.indexOf('<div id="cart_content">')+23;
            var end2= xhr.responseText.indexOf("</div>",start2);
            $$('.top-link-cart').each(function (el){
                el.innerHTML = xhr.responseText.substring(start2,end2);
            });
			
			$$('cart-content').each(function (el){
                el.replace(xhr.responseText.substring(start4,end4));
                //new Effect.Opacity(el, { from: 0, to: 1, duration: 1.5 });
            });
            var start4 = xhr.responseText.indexOf('<div class="cart_side_ajax">')+28;
            var end4 = xhr.responseText.indexOf("<span>j2t_ajax_auto_add</span></div>",start4);
			var start5 = xhr.responseText.indexOf('<div class="cart_side_title_ajax">')+34;
                var end5 = xhr.responseText.indexOf("<span>j2t_ajax_auto_add</span></div>",start5);

                $$('.mini-products-list').each(function (el){
                    el.replace(xhr.responseText.substring(start4,end4));
                    //new Effect.Opacity(el, { from: 0, to: 1, duration: 1.5 });
                });
                $$('.top-block-cart').each(function (el){
                    el.replace(xhr.responseText.substring(start4,end4));
                    //new Effect.Opacity(el, { from: 0, to: 1, duration: 1.5 });
                });
				$$('.header-cart-title').each(function (el){
                    el.replace(xhr.responseText.substring(start5,end5));
                    //new Effect.Opacity(el, { from: 0, to: 1, duration: 1.5 });
                });

			if(jQuery('.payment-methods').Jexists())
				jQuery('.payment-methods input:checked').focus().click();
            replaceDelUrls();

            //$('j2t_ajax_progress').hide();
            hideJ2tOverlay();
            jQuery('#cart-content').hide();

        }

    });


}

function showJ2tOverlay(){
    new Effect.Appear($('j2t-overlay'), { duration: 0.5,  to: 0.8 });
}

function hideJ2tOverlay(){
    $('j2t-overlay').hide();
    $('fusebox_ajax_progress').hide();
    $('j2t_ajax_confirm').hide();
}


function j2tCenterWindow(element) {
     if($(element) != null) {

          // retrieve required dimensions
            var el = $(element);
            var elDims = el.getDimensions();
            var browserName=navigator.appName;
            if(browserName==="Microsoft Internet Explorer") {

                if(document.documentElement.clientWidth==0) {
                    //IE8 Quirks
                    //alert('In Quirks Mode!');
                    var y=(document.viewport.getScrollOffsets().top + (document.body.clientHeight - elDims.height) / 2);
                    var x=(document.viewport.getScrollOffsets().left + (document.body.clientWidth - elDims.width) / 2);
                }
                else {
                    var y=(document.viewport.getScrollOffsets().top + (document.documentElement.clientHeight - elDims.height) / 2);
                    var x=(document.viewport.getScrollOffsets().left + (document.documentElement.clientWidth - elDims.width) / 2);
                }
            }
            else {
                // calculate the center of the page using the browser andelement dimensions
                var y = Math.round(document.viewport.getScrollOffsets().top + ((window.innerHeight/2)- $(element).getHeight()));
                var x = Math.round(document.viewport.getScrollOffsets().left + ((window.innerWidth - $(element).getWidth()))/2);
            }
            // set the style of the element so it is centered
            var styles = {
                position: 'absolute',
                top: y + 'px',
                left : x + 'px'
            };
            el.setStyle(styles);




     }
}

function showLoading(on, text){
	var spinnerImg = 'spinner_green.gif';
    if(on){
    	jQuery('#fusebox_ajax_progress_text').text(text);
 	    if(!jQuery('#fusebox_ajax_progress').is(':visible')){
    		jQuery('#fusebox_ajax_progress_spinner').attr('src', '/skin/frontend/default/pumabikes/images/loader/'+spinnerImg );
 	    	var progress_box = $('fusebox_ajax_progress');
 	    	progress_box.style.height = 184 + 'px';
 	    	progress_box.style.width = 224 + 'px';
 	    	progress_box.style.position = 'absolute';
    		progress_box.show();
    		j2tCenterWindow(progress_box);
    	}
    } else {
    	jQuery('#fusebox_ajax_progress').hide();
    }
    
}


function showConfirm(){
    showLoading(false);
    var confirm_box = $('j2t_ajax_confirm');
    confirm_box.show();
    confirm_box.style.width = confirmW + 'px';
    confirm_box.style.height = confirmH + 'px';

    confirm_box.style.position = 'absolute';

    j2tCenterWindow(confirm_box);

}

function showConfirmBike(continuetocheckout){

	var SelectedValues = new Array();           
    jQuery('#product-options-wrapper label').each(function(i, selected){        
			SelectedValues[i] = '<strong>'+jQuery(selected).text().replace(/\*/ig, "")+':</strong> ';
    });   
	jQuery('#product_addtocart_form :selected').each(function(i, selected){
			//jQuery(selected).parent('select').attr('id').replace(/attribute/ig, "") +'  '+
		SelectedValues[i] = SelectedValues[i] + (jQuery(selected).text());
	});
	var confirmIt = '<div class="want-to-buy-this"><table width="100%" border="0" cellspacing="0" cellpadding="0"><tr><td id="sb-tl"></td><td id="sb-tc"></td><td id="sb-tr"></td></tr><tr><td id="sb-cl"></td><td id="sb-cc"><div id="sb-nav-close"></div><h2>Confirm your bike configuration</h2>';
	confirmIt += '<br/><p><strong>Bike type:</strong> '+jQuery('.product-name h1 span').text() + '</p>';
	SelectedValues.each(function(i, selected){
		confirmIt += '<p>' +i+'</p>';
	});
	confirmIt += '<div class="approve-button"><span class="hide">Approve</span></div></td><td id="sb-cr"></td></tr><tr><td id="sb-bl"></td><td id="sb-bc"></td><td id="sb-br"></td></tr></table></div>';
	showLoading(false);
    var confirm_box = $('confirm-buy');
    
    confirm_box.innerHTML = confirmIt;
    confirm_box.show();
    confirmW = 290;
        //j2tCenterWindow(confirm_box);
	jQuery('.approve-button').click(function(){
		if(continuetocheckout){
			jQuery('#docheckout').click();
		}else{
			jQuery('#btn-to-cart').click();
		}
		confirm_box.innerHTML = '';
		hideJ2tOverlay();
		showLoading(true, 'Adding to shopping bag..');
	});
	
	jQuery('.want-to-buy-this #sb-nav-close').click(function(){
		confirm_box.innerHTML = '';
		hideJ2tOverlay();
	});

}

function showBikeSize(){

	
	var BikeSize = '<div class="size-info"><table width="100%" border="0" cellspacing="0" cellpadding="0"><tr><td id="sb-tl"></td><td id="sb-tc"></td><td id="sb-tr"></td></tr><tr><td id="sb-cl"></td><td id="sb-cc"><div id="sb-nav-close"></div><h2>More about sizes</h2>';
	BikeSize += jQuery("#size-description").html();
BikeSize += '</td><td id="sb-cr"></td></tr><tr><td id="sb-bl"></td><td id="sb-bc"></td><td id="sb-br"></td></tr></table></div>';
	showLoading(false);
    var size_box = $('size-info');
    
    size_box.innerHTML = BikeSize;
    
    size_box.style.width = 620 + 'px';
    size_box.style.height = confirmH + 'px';
	size_box.style.top = '0px';
	size_box.style.right = '0px';
    size_box.style.position = 'absolute';
    size_box.show();
    //confirmW = 290;
        //j2tCenterWindow(confirm_box);
	
	
	jQuery('#sb-nav-close').click(function(){
		size_box.innerHTML = '';
		size_box.hide();
		hideJ2tOverlay();
	});

}



document.observe("dom:loaded", function() {
    replaceDelUrls();
    replaceAddUrls();
    //Event.observe($('j2t-overlay'), 'click', hideJ2tOverlay);

    var cartInt = setInterval(function(){
        if (typeof productAddToCartForm  != 'undefined'){
            if ($('j2t-overlay')){
                Event.observe($('j2t-overlay'), 'click', hideJ2tOverlay);
            }
            productAddToCartForm.submit = function(sendtocheckout){
                if(this.validator && this.validator.validate()){
					if(!jQuery('.approve-button').Jexists()){
						showConfirmBike(sendtocheckout);
                        return false;
					} else {
                    	sendcart('', 'form', sendtocheckout);
                    	clearInterval(cartInt);
                    }
                }

                return false;
            }
        } else {
            clearInterval(cartInt);
        }
    },500);
});

