//Javascript manipulation for Cart with JQuery
//@author Udana Udayanga <udana@proporta.com>
//@date 2009-06-25

var ajaxManager,ajaxManager2;

$(document).ready(function(){

    $("#spProducts").fadeIn("slow");

    $('#mycarousel').jcarousel({
        wrap:'both',
        scroll:1,
        auto:3,
        animation:'slow'
    });

    $(".decItem").live("click", sendAction);
    $(".removeItem").live("click", sendRemoveAction);    
    $(".decItemSpo").live("click", sendAction);
    $(".removeItemSpo").live("click", sendRemoveAction);
    $(".removeItemFree").live("click", sendNoRefreshAction);

    $(".incItem").live("click", sendNoRefreshAction);
    $(".incItemSpo").live("click", sendNoRefreshAction);
   
    if($.browser.msie)
    {
         $(".features").live("click", chngProVariantAction);
         $(".features2").live("click", chngSpVariantAction);
         $(".proList").live("click", chngFreeProAction);
    }
    else
    {
         $(".features").live("change", chngProVariantAction);
         $(".features2").live("change", chngSpVariantAction);
         $(".proList").live("change", chngFreeProAction);
    }

    $(".proQuantity").live("keyup", updateQuantityAction);
    $(".spQuantity").live("keyup", updateSpQuantityAction);
    

    $(".proQuantity").noContext();
    $(".spQuantity").noContext();

    $("#deliveryMethod").live("click",deliveryPop);

    ajaxManager = $.manageAjax.create('cartQueue', {
            queue: true,            
            cacheResponse: false            
    });

    ajaxManager2 = $.manageAjax.create('cartQueue2', {
            queue: true,
            cacheResponse: false            
    });

    equalHeight($(".heading"));
    equalHeight($(".image_container"));
    equalHeight($(".prices"));

    

});


    function deliveryPop()
    {   
        $this = $(this);
        $href = $this.attr("href");
       
        $("#delivery_pop").attr("href",$href);

        $("#delivery_pop").trigger("click");

        return false;
    }

    function showPreloader()
    {
        if (jQuery.browser.msie)
        {
            if(parseInt(jQuery.browser.version) != 6)
                $("#preloader").fadeIn();
        }
        else
        {
            $("#preloader").fadeIn();
        }
    }


    function equalHeight(group) {
        tallest = 0;
        group.each(function() {
            thisHeight = $(this).height();
            if(thisHeight > tallest) {
                tallest = thisHeight;
            }
        });
        group.height(tallest);
    }
    
    function sendAction()
    {
        $this	= $(this);
        $url		= $this.attr("href");
        showPreloader();
         
        if($this.next().val() == 1)
        {
            sendRequest($url);
        }
        else
        {           
            sendNoRefreshRequest($url);
        }

        return false;
    }

    function sendRemoveAction() {
        
        $this	= $(this);
        $url		= $this.attr("href");

        showPreloader();
        sendRequest($url);

        return false;
    }

    function sendNoRefreshAction()
    {
        
        $this	= $(this);
        $url		= $this.attr("href");
        showPreloader();
        sendNoRefreshRequest($url);

        return false;
    }

    function updateShipping($id, $url)
    {
        $url = $url+"?radiobutton="+$id;

        showPreloader();
        sendNoRefreshRequest($url);

        return false;
    }

    function chngShippingCountry($id, $url)
    {
	
	$url = $url+"?country="+$id;
	//alert($url);
	//showPreloader();
        ajaxRequestManager($url,'#deliveryPopup');
	return false;
    }

    function chngFreeProAction()
    {
        $this	= $(this);
        $mr = $this.parent().eq(0).attr('name');
        url		= $this.parent().eq(0).attr("action");

        $proid = $("#proid3"+$mr).val();
        $varid = $("#varid3"+$mr).val();

        $url = url+"?mrId="+$mr+"&proString="+$this.val()+"&proid="+$proid+"&varid="+$varid;

        if(parseInt($this.val())!= parseInt($varid))
        {
            showPreloader();
            sendNoRefreshRequest($url);
        }

        return false;
    }

    function chngProVariantAction()
    {        
        $this	= $(this);        
        proD = $this.parent().eq(0).attr('name');
        url		= $this.parent().eq(0).attr("action");
        $proid = $("#proid"+proD).val();
        $varid = $("#varid"+proD).val();

        $url = url+"?proid="+$proid+"&varid="+$varid+"&features="+$this.val();

        if(parseInt($this.val())!= parseInt($varid))
        {
            showPreloader();
            sendNoRefreshRequest($url);
        }

        return false;
    }

    function chngSpVariantAction()
    {

        $this	= $(this);
        proD = $this.parent().eq(0).attr('name');
        url		= $this.parent().eq(0).attr("action");
        $proid = $("#proid2"+proD).val();
        $varid = $("#varid2"+proD).val();

        $url = url+"?proid="+$proid+"&varid="+$varid+"&features="+$this.val();

        if(parseInt($this.val())!= parseInt($varid))
        {
            showPreloader();
            sendNoRefreshRequest($url);
        }

        return false;
    }

    var numb = "0123456789";

    function updateQuantityAction(e)
    {
        $this	= $(this);
        $t = $this.attr('id');
        $vv = $this.val();

        var w = "";
        for (i=0; i < $vv.length; i++)
        {
            x = $vv.charAt(i);
            if (numb.indexOf(x,0) != -1)
            {
                w += x;
            }
            else
            {
                w = 1;
            }
        }


         if((w =='')||(w == 0)) w = 1;

        url		= $this.attr("name");
        $varid = $("#varid"+$t).val();
        $quantity = w;

        $url = url+"?proid="+$t+"&quantity="+$quantity+"&varid="+$varid;

        if(secs!=0)        
            InitializeTimer($url);            
        
        return false;
    }
   
//////////////////////////// Start :Script to manage Time for Quantity box ///////////////////////////////////////////////////////
var secs
var timerID = null
var timerRunning = false
var delay = 1000

function InitializeTimer($url)
{
    // Set the length of the timer, in seconds
    secs = 2
    StopTheClock()
    StartTheTimer($url)    
}

function StopTheClock()
{
    if(timerRunning)
        clearTimeout(timerID)
    timerRunning = false
}

function StartTheTimer($url)
{
    if (secs==0)
    {
        StopTheClock()
        // Here's where you put something useful that's
        // supposed to happen after the allotted time.
        // For example, you could display a message:
        showPreloader();
        sendNoRefreshRequest($url);
        
    }
    else
    {
        self.status = secs
        secs = secs - 1
        timerRunning = true
        timerID = self.setTimeout("StartTheTimer($url)", delay)
    }
}
    
/////////////////////////// End :Script to manage Time for Quantity box ////////////////////////////////////

function updateSpQuantityAction()
{
    $this	= $(this);
    proD = $this.attr('id');
    $vv = $this.val();


    var w = "";
    for (i=0; i < $vv.length; i++)
    {
        x = $vv.charAt(i);
        if (numb.indexOf(x,0) != -1)
        {
            w += x;
        }
        else
        {
            w = 1;
        }
    }

     if((w =='')||(w == 0)) w = 1;
    
	url		= $this.attr("name");    
    $varid = $("#varid2"+proD).val();
    $quantity = w;

    $url = url+"?proid="+proD+"&quantity="+$quantity+"&varid="+$varid;

    if(secs!=0)
            InitializeTimer($url);      

	return false;
}

function sendNoRefreshRequest($url)
{
     
     ajaxManager.add({
      success: function(html) {         
         $("#review_cart").html(html);
         $("#preloader").fadeOut();
         secs = 2;
         refreshYourBasket2();
         refreshMrBanners();
         refreshCheckoutPromotion();
      },
      url: $url
    });
     
}

function sendRequest($url)
{
     ajaxManager.add({
      success: function(html) {
         $("#review_cart").html(html);
         $("#preloader").fadeOut();
         otherRequests();
      },
      url: $url
    });    
}

function otherRequests()
{
    refreshYourBasket2();
    refreshAddFreeProduct();
    refreshMrBanners();
    refreshCheckoutPromotion();
    refreshRecomendedProducts();
}

function refreshYourBasket()
{
    $url = _baseURL+"/cart/your-basket";
    ajaxRequestManager($url,".your_basket");
}

function refreshYourBasket2()
{
    $url = _baseURL+"/cart/your-basket";
    ajaxRequestManager2($url,".your_basket");
}

function refreshRecomendedProducts()
{
    $url = _baseURL+"/cart/sp-offer-products";
    ajaxRequestManager2($url,"#spProducts");
}

function refreshAddFreeProduct()
{
    $url = _baseURL+"/cart/ad-free-product";
   ajaxRequestManager2($url,"#addFreProduct");
    
}

function refreshMrBanners()
{
    $url = _baseURL+"/cart/mr-banners";
   ajaxRequestManager2($url,"#mr_banners");

}

function refreshCheckoutPromotion()
{
    $url = _baseURL+"/cart/checkout-promo";
     ajaxRequestManager2($url,"#promoChkout");

}

function ajaxRequestManager($url,$element)
{
    ajaxManager.add({
      success: function(html) {
         $($element).html(html);
         $("#preloader").fadeOut();
      },
      url: $url
    });
}

function ajaxRequestManager2($url,$element)
{
    ajaxManager2.add({
      success: function(html) {
         $($element).html(html);         
      },
      url: $url
    });
}

function setQuickCheckout()
{
    $("#chk_qc").val("true");
}

function validateEmail( strValue) {

	var objRegExp	 = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*\.(\D{2}|(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum|asia|cat|jobs|mobi|tel|travel))$/i;
	//var objRegExp  = /^[a-z0-9]([a-z0-9_\-\.]*)@([a-z0-9_\-\.]*)(\.[a-z]{2,3}(\.[a-z]{2}){0,2})$/i;		
	return objRegExp.test(strValue);
}

function OpenNewWindow(location,param,width,height)
{
    window.open(location + '?' + param , ''
            , 'location=no,menubar=no,resizable=yes,scrollbars=yes,status=no,toolbar=no,width='
                + width	+',height='	+ height + ',top='+ (screen.height-height)/2 + ',left=400');
}

