jQuery.fn.exists = function() { return (this.length > 0); };
var page = 0;


jQuery(function(){
     
    lastBlock = $("#expanded");
    maxWidth = 600;
    minWidth = 43;    

    $("ul li.accordian a").hover(
    
    function(){
        $(lastBlock).animate({width: minWidth+"px"}, { queue:false, duration:400 });
        $(this).animate({width: maxWidth+"px"}, { queue:false, duration:400});
        lastBlock = this;
        }
    ); 
    
    lastBlock = $("#products-expanded");
    productMaxWidth = 200;
    productMinWidth = 43;    

    $("ul li.product-accordian a").hover(
    
    function(){
        $(lastBlock).animate({width: productMinWidth+"px"}, { queue:false, duration:400 });
        $(this).animate({width: productMaxWidth+"px"}, { queue:false, duration:400});
        lastBlock = this;
        }
    );
    

    Cufon.replace($('.cufon'));
    $('#main-navigation li').hover(
        function() {
            if($(this).find('.main-nav-box').is(':hidden'))
                $(this).find('.main-nav-box').slideDown('fast');   
        },
        function() {
            $(this).find('.main-nav-box').slideUp('fast');     
        }
    );
    
    $('.jshide').hide();
    
    $('input[name="category[]"],input[name="material[]"],input[name="gem[]"],select[name="sort"],select[name="pp"]').live('change',function(){
        refreshProducts();
    });
    
    $('.toggle-checkbox').live('click', function(){
        //alert('clicked checkbox');
        $(this).closest('ul').find('.toggle-checkbox').each(function(){
            var checkbox = $(this).siblings('input[type="checkbox"]');
            checkbox.attr('checked','');   
            $(this).closest('li').removeClass('selected');                    
        });
        var checkbox = $(this).siblings('input[type="checkbox"]');
        if(checkbox.is(':checked')) {
            //alert('checked');
            checkbox.attr('checked',''); 
            $(this).closest('li').removeClass('selected');
        } else {
            //alert('not-checked');
            checkbox.attr('checked','checked');   
            $(this).closest('li').addClass('selected');
        }                   
        checkbox.trigger('change');                    
        
        return false;
    });
    
    $('input[name="category[]"],input[name="material[]"],input[name="gem[]"]').live('click', function(){
        
    });
    
    $('#paginate a').live('click', function(){
        var data = getURLArguments($(this).attr('href'));
        if(data['p']!='undefined')
            page = data['p'];
            
        refreshProducts();
        return false;
    });
    
    $('#help-topics a:not(#help-topics ul a)').click(function(){   
        var hasClass = $(this).hasClass('selected');
        $('#help-topics a').removeClass('selected'); 
        $('#help-topics ul').hide();
        $('#topic-panel div').hide();
        if(!hasClass) {
            $(this).addClass('selected');
            var el=$(this).attr('href');
            el=el.substr(el.indexOf('#'));
            $(el).show();            
        }   
        return false;
    });
    
    $('#help-topics ul a').click(function(){
        var hasClass = $(this).hasClass('selected');   
        $('#help-topics ul a').removeClass('selected'); 
        $('#topic-panel div').hide();
        if(!hasClass) {
            $(this).addClass('selected');
            var el=$(this).attr('href');
            el=el.substr(el.indexOf('#'));
            $(el).show();            
        }
        
        return false;
    });    
    
    $('#box-control li a').click(function(){
        $('#box-control li').removeClass('selected');
        $('#box div').hide(); 
        $(this).closest('li').addClass('selected'); 
        var el=$(this).attr('href');
        el=el.substr(el.indexOf('#'));
        $(el).show();   
        return false;        
    });
    
    $('#box div').hide();
    $('#box div:first').show();
    
    $('a[rel="external"]').click(function(){
        window.open( $(this).attr('href') );
        return false;        
    });
    
    //$('#product-main').html($('#product-main form:first fieldset').html());
    
    $('input.radio[name="billingindex"], input.radio[name="shippingindex"]').change(function(){
        updateIndexes();
    });
    
    $('select[name="d"]').change(function(){
        var newLoc = window.location.toString();
        var idx = newLoc.indexOf('?');
        if(idx != -1)
            newLoc = newLoc.substr(0,idx);
            
        window.location = newLoc+'?d='+$('select[name="d"]').val();
    });
    
    $('#update-bag').click(function(){
        $(this).closest('fieldset').append($('<input type="hidden" name="updateBasket" value="1" />'));
        $(this).closest('form').submit();
        return false;
    });
    
    $('#empty-bag').click(function(){
        $(this).closest('fieldset').append($('<input type="hidden" name="emptyBasket" value="1" />'));
        $(this).closest('form').submit();
        return false;
    });
    
    $('select[name="payment-type"]').change(function(){
        updatePaymentForm();
    });
    
    $('#search .button.submit, #newsletter .button.submit').click(function(){
        $(this).closest('form').submit();
    });
    
    /*$('#news-feed').cycle({
        fx:         'scrollVert',
        pause:      1, 
        timeout:    10000 
    });*/
    
    $('#recently-viewed, #best-sellers').cycle({
        fx:         'scrollHorz',
        pause:      1,
        timeout:    10000 
    });
    
    $('.arrow.left a').click(function(){
        $('#recently-viewed, #best-sellers').cycle('prev'); 
        return false;       
    });
    
    $('.arrow.right a').click(function(){
        $('#recently-viewed, #best-sellers').cycle('next');    
        return false;    
    });
    
    $('#currency').hover(
        function(){
        },        
        function(){ 
            $('#currency ul').animate({
                height:     'hide'
            },100);            
        }
    );
    
    $('#currency #select-currency').click(function(){  
        $('#currency ul').animate({
            height:     'show'
        },100);    
        return false;
    });
    
    $('#currency ul li a').click(function(){
        var data = getURLArguments($(this).attr('href'));
        var cur = 'GBP';
        if(data['cur']!='undefined')
            cur = data['cur'];
            
        $.post('/ajax',
        {
            'act': 'ucurrency',
            'currency': cur        
        },
        function(data){
            if(data.error) {
                alert(data.error);
                return;
            }    
            window.location.reload();    
        },'json');  
        return false;      
    });
    
    $('#sub-images li a').click(function(){
        $('#main-images li').hide();
        var el=$(this).attr('href');
        el=el.substr(el.indexOf('#'));
        $(el).show();   
        $('#zoom').attr('href',$(el).find('a:first').attr('href'));
        MagicZoom.refresh(); 
        return false;          
    });
    
    $('#main-images li:first').show();
    
    $('.product #product select[name="opt"]').change(function(){
        $('.product #product #colour').html('<img src="/media/images/icons/ajax-loader-smallest.gif" alt="Loading..." />');
        $.post('/ajax',
        {
            'act': 'uopt',
            'opt': $('.product #product select[name="opt"]').val(),
            'p_id': $('input[name="p_id"]').val()        
        },
        function(data){
            if(data.error) {
                alert(data.error);
                return;
            }    
            $('.product #product #colour').html(data.result);    
        },'json');
    });
    
    /*$('.addbag').click(function(){
        var ob_id = $(this).parent().find('input[name="p_id"]').val();
        alert(ob_id);
        var li = $(this).closest('li');
        li.css('position','relative');
        var div = $('<div class="product-options"></div>')
        return false;
    });*/
    
    /*$('input.addbag').click(function(){
        if($(this).attr('disabled')!='undefined') {
            alert('Sorry this item is currently out of stock'); 
            return false;
        }
    });*/
    
    $('#search input[name="s"]').click(function(){
        if($(this).val()=='I\'m looking for...')
            $(this).val('');
             
    }); 
    
    if($('#refine-panel').exists() && $('#refine-panel').css('height')=='0px') {
        //$('#products-panel').css('width','auto');
    }

    unFocus.History.addEventListener('historyChange', historyListener);
    historyListener(unFocus.History.getCurrent());  
    
});

function addHistoryEntry(val) { // Expects a javascript object
    var str = '';
    for(key in val) {
        str += '&'+key+'='+val[key];
    }
    unFocus.History.addHistory(str);    
}
   

function historyListener(historyHash) {
    if(historyHash) {
        historyHash += '&act=plist';
        //var data = $.evalJSON(historyHash);
        LoadOverlay('show');
        $.post('/ajax',
        historyHash, 
        function(data){
            if(data.error) {
                alert(data.error);
                return;
            }
            $('#products-panel').html(data.result.products);
            $('#refine-panel').html(data.result.refine);
            $('.jshide').hide();
            page = 0;
            LoadOverlay('hide');
            /*$('#refine-panel input[type="checkbox"]').each(function(){
                var el = $('<div class="checkbox-cover '+($(this).is(':checked')?'checked':'')+'"></div>');
                el.click(function(){
                    $(this).toggleClass('checked');
                    $(this).parent().find('label input').trigger('click');    
                }); 
                $(this).closest('li').append(el)
            });*/
        },'json');
    }
};         

function updatePaymentForm() {
    $('#payment-form').html('<img src="/media/images/icons/ajax-loader-small.gif" alt="Loading..." />');
    $.post('/ajax',
    {
        'act': 'upayment',
        'payment-type': $('select[name="payment-type"]').val()        
    },
    function(data){
        if(data.error) {
            alert(data.error);
            return;
        }    
        $('#payment-form').html(data.result);    
    },'json');
}

function updateIndexes() {
    $.post('/ajax',
    {
        'act': 'uindexes',
        'billingindex': $('input.radio[name="billingindex"]:checked').val(),
        'shippingindex': $('input.radio[name="shippingindex"]:checked').val()
    }, 
    function(data){
        if(data.error) {
            alert(data.error);
            return;
        }
    },'json');    
    return false;
}

function getURLArguments(href) {
    var idx = (href.indexOf('?')==-1)?href.indexOf('&'):href.indexOf('?');
    var params = new Array();
    if (idx != -1) {
        var pairs = href.substring(idx+1, href.length).split('&');
        for (var i=0; i<pairs.length; i++) {
            nameVal = pairs[i].split('=');
            params[i] = nameVal[1];
            params[nameVal[0]] = nameVal[1];
        }
    }
    return params;
}

function refreshProducts() {
    LoadOverlay('show');
    //var optName = $('input[name="optname"]').val();
    var terms = $('input[name="terms"]').val();
    var categoryData = [];
    $('input[name="category[]"]:checked').each(function(){
        categoryData.push($(this).val());
    });
    /*var optData = [];
    $('input[name="'+optName+'[]"]:checked').each(function(){
        optData.push($(this).val());
    });  
    var materialData = [];
    $('input[name="material[]"]:checked').each(function(){
        materialData.push($(this).val());
    });       
    var gemData = [];
    $('input[name="gem[]"]:checked').each(function(){
        gemData.push($(this).val());
    });*/ 
    var data = {
        'category': categoryData,
        'id' : $('input[name="id"]').val(),
        //'opt': optData,
        //'optname' : optName,
        //'material': materialData,
        //'gem': gemData,
        'sort': $('select[name="sort"]').val(),
        'pp': $('select[name="pp"]').val(),
        'p': page,
        'terms': terms
    }  
    addHistoryEntry(data);
}

function LoadOverlay(display) {
    if(display=='hide') {
        $('#load-overlay').hide();
    } else if (display=='show') {
        var height = $('#products-panel').css('height').split('px'); height = height[0];
        var margin = Math.ceil((height/2))+'px auto'; 

        $('#load-overlay').css('height',height+'px');
        $('#load-overlay #load-box').css('margin',margin);
        $('#load-overlay').show(); 
    }
}

function dump(arr,level) {
    var dumped_text = "";
    if(!level) level = 0;
    
    //The padding given at the beginning of the line.
    var level_padding = "";
    for(var j=0;j<level+1;j++) level_padding += "    ";
    
    if(typeof(arr) == 'object') { //Array/Hashes/Objects 
        for(var item in arr) {
            var value = arr[item];
            
            if(typeof(value) == 'object') { //If it is an array,
                dumped_text += level_padding + "'" + item + "' ...\n";
                dumped_text += dump(value,level+1);
            } else {
                dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
            }
        }
    } else { //Stings/Chars/Numbers etc.
        dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
    }
    return dumped_text;
}
