var isHome = false;
var dropdownOn = false;   
var fadeOutTimer = "";  


function zoom(){ 
    $("#zoom").anythingZoomer({
        smallArea   : 'small',    // class of small content area; the element with this class name must be inside of the wrapper
        largeArea   : 'large',    // class of large content area; this class must exist inside of the wrapper. When the clone option is true, it will add this automatically
        clone       : false,      // Make a clone of the small content area, use css to modify the style
        switchEvent : 'dblclick', // event that allows toggling between small and large elements - default is double click
        edge        : 30          // How far outside the wrapped edges the mouse can go; previously called "expansionSize"
    });
}

$(document).ready(
    function(){
        var img = new Image();       
        img.src = $('.getSize').attr('src');
        $('.getSize').attr('src');
        img.onload = function(){
            var height = $('.getSize').height();
            $('.small .getSize').height(height);
            $('.large img').show();
            zoom();
        }  
 
        //Basket options hover
        var alreadyGoing = false;
        $('.optionButtonLeft').each(
            function(){
                $(this).hover(   
                    function(){
                        if(!alreadyGoing){
                            alreadyGoing = true;
                            $(this).prev().children('.optionsDropown').fadeIn('fast', function(){alreadyGoing = false;});
                        }
                    },
                    function(){ 
                        $(this).prev().children('.optionsDropown').fadeOut('fast');
                    }
                );
            }
        );
    
        // Slider 
        var sections = []; 
        var sumOfSections = 0;
        var currentBackground = '';
        var backSet = false;
        
        $( '.section' ).each(
            function(){
                sections.push( $(this).width() );  
            }
        );      
        
        //  Get section length
        
        for( a in sections ){
            sumOfSections += sections[a];                   
        }
        
        $( '#slider' ).width( ( sumOfSections ) );
        
        // Load first range image
        
                                   
        // Nav hovers   
            
        $('#mainLinks ul li, #footer ul li').hover(
            function(){
                $(this).children('ul.children').show();        
            },
            function(){
                $(this).children('ul.children').hide();
            }
        );
        
        var thirdWidth = $('#mainLinks ul li ul').width();
        
        $('#mainLinks ul li ul li ul').css('margin-left', thirdWidth);
            
        if(isHome){
            var firstRangeImage = $('.range').eq(0).attr('rangeImage');
            $('#theImage').html('<img src = "' + firstRangeImage + '" />');  
                                                    
            // Nav hovers
            
            $('ul li.range').click(
                function(){
                    $('ul li.range').children('a').css('background-image', 'none');                        
                    backSet = true;
                    $(this).children('a').css('background-image', 'url("' + siteUrl + '/images/bullet-point.png")');  
                }
            ); 
            
            function setOutside(obj){             
                currentBackground = $(obj).children('a').css('background-image'); 
                 
                $(obj).children('a').css('background-image', 'url("' + siteUrl + '/images/bullet-point.png")');   
            }
            
            $('ul li.range').hover(
                function(){                             
                    setOutside($(this));               
                },
                function(){
                    if(currentBackground != 'url("' + siteUrl + '/images/bullet-point.png")' && !backSet){
                        $(this).children('a').css('background-image', 'none');
                    }  
                    backSet = false;
                }
            );
        }
        
        $('.aTabLeft').eq(0).css('background-image', 'url("' + siteUrl + '/images/tab-left-chosen.jpg")');
        $('.aTabMiddle').eq(0).css('background-color', '#e4ddcf');              
        $('.aTabRight').eq(0).css('background-image', 'url("' + siteUrl + '/images/tab-right-chosen.jpg")'); 
        
        $('.aTabMiddle').click(
            function(){  
                var related = $(this).attr('related');
                if(related != 'five'){            
                    $('.aTabLeft').css('background-image', 'url("' + siteUrl + '/images/tab-left.jpg")');
                    $('.aTabMiddle').css('background-color', '#dbd1c9');              
                    $('.aTabRight').css('background-image', 'url("' + siteUrl + '/images/tab-right.jpg")'); 
                        
                    $(this).css('background-color', '#e4ddcf');
                    $(this).prev().css('background-image', 'url("' + siteUrl + '/images/tab-left-chosen.jpg")');
                    $(this).next().css('background-image', 'url("' + siteUrl + '/images/tab-right-chosen.jpg")');     
                    $('.tabRightContent').hide();
                    $('#' + related).show();
                }
            }
        );
          
        var imgWidth = 0;
        
        $('.shareButton span img').each(
            function(){
                imgWidth += ( parseInt( $(this).width() ) );
                $(this).width(0);   
            }
        );  
        var imgMargin = parseInt( $('.shareButton span img').eq(0).css( 'margin-left' ) ); 
        $('.shareButton span img').css( 'margin-left', '0px' ); 
                            
        var notFinished = false;
        $('.shareButton').hover(
            function(){                 
                if(!notFinished){  
                    notFinished = true;  
                    //alert(imgWidth - ( imgMargin * $('.shareButton span img').length ) / $('.shareButton span img').length );
                    $('.shareButton span img').animate({ 
                        width: ( imgWidth - ( imgMargin * $('.shareButton span img').length ) ) / $('.shareButton span img').length, 
                        marginLeft: 5 
                    }, function(){
                    notFinished = false;});
                }
            },
            function(){                             
                $('.shareButton span img').animate({
                    width: 0, 
                    marginLeft: 0 
                });       
            }
        );
        
        /*alert($('#four .galleryTab').css('display'));
        if($('#four .galleryTab').css('display') == 'none'){
            $('.galleryTab').hide();
        }*/
        
        var firstRangeImageDropDown = $('li.dropDownRange').eq(0).attr('rangeImage');    
        $('#dropdownImage').html('<img src = "' + firstRangeImageDropDown + '" />');
        
        // Set shopping cart price and items 
        
            
        //Room dropdown
        
       $('.room').hover(
            function(){     
                $(this).removeClass('hover');  
                $(this).unbind('click');
                var width = $(this).position();    
                var height = $(this).height();    
                $('table', this).css('left', width.left + 'px');  
                $('table', this).css('top', ( width.top + height ) + 'px');
                $(this).css('background-color', '#F3EBE2');
                $('table', this).show();   
                getWidth = $('table', this).width();       
                if($('table', this).position().left + getWidth > 935){   
                    $('table', this).css('left', 'auto');  
                    $('table', this).css('right', '0px');    
                }
            },
            function(){        
                $('table', this).hide();
                fadeOutRoomDropdownMenu($('table', this), $(this)); 
            }
        );
                       
        //Ranges dropdown
        
        var rangePos = $('#navigation .page-item-1500').position(); 
        $('#navigation .page-item-1500 a').click(
            function(e) {
                e.preventDefault();
            }
        );

        $('#navigation .page-item-1500').hover(
            function(){        
                clearTimeout(fadeOutTimer);
                    
                $(this).removeClass('hover');
                $(this).css('background-color', '#F3EBE2');
                
                dropdownMenu();
            },
            function(){
                fadeOutTimer = setTimeout(function(){
                    fadeOutDropdownMenu();
                }, 10);
            }
        );
        
        $('.dropdown').css('left', rangePos.left);
        
    
        $('.dropdown').hover(
            function(){  
                clearTimeout(fadeOutTimer);
            },
            function(){
                fadeOutTimer = setTimeout(function(){
                    fadeOutDropdownMenu();
                }, 10);
            }
        );     
    }                                                         
);

$(window).load(
    function(){ 
        $('#loading').show(); 
        $('#loading').css('visibility', 'visible');
        $('#loadingBasket').hide();
    }
);

function loadRoomImage(imgSrc, obj){
    $(obj).parent().parent().parent('td .navDropdownImage img').attr('src', imgSrc);
}
 
function fadeOutRoomDropdownMenu(obj, obj2){
    $(obj).hide(); 
    $(obj2).css('background-color', 'transparent');  
}

function dropdownMenu(){  
    $('.dropdown').show();    
}

function fadeOutDropdownMenu(){
    $('.dropdown').hide(); 
    $('.page-item-1500').css('background-color', 'transparent'); 
    dropdownOn = false;  
}
    
var currentCategory = false;
var fadeCategory = true;

function load_categories(range, page, movement, obj){
    $('#categoryText').fadeIn();

    if(page == 'product-page'){  
        if(movement == 'next'){
            var direction = '-';  
            var amount = direction + '250';
        }else{      
            var amount = 0;
        }
    }else{      
        var direction = '-';        
        var amount = direction + '296';
    }
        
    if(currentCategory != range){
        $('.category').each(
            function(){
                if($(this).attr('range') != range){
                    $(this).hide();
                }
            }
        );
    }
    
    currentCategory = range;  
    
    if(fadeCategory){  
        $('.category').each(
            function(){
                if($(this).attr('range') == range){
                    $(this).fadeIn();
                }
            }
        );
        
        $('#slider').animate({
            left:amount
        });
    }
}

function load_range_image(image, location){
    switch(location){
        case 'slider':
                $('#theImage').html('<img src = "' + image + '" />');
            break;
        case 'nav':        
                $('#dropdownImage').html('<img src = "' + image + '" />');
            break;
    }
                
}

function load_product_image(src, obj){
    //alert(src);
    //alert($(obj).parent().parent().next().find('.navDropdownImage img').attr('src'));
    $(obj).parent().parent().next().find('.navDropdownImage img').attr('src', src);
}

// The shopping cart

var shoppingCart = new Object;
var productMatrix = new Array();

var product = function(id, price, sku, quantity, options){
    this.id = id;
    this.price = price;   
    this.sku = sku;
    this.quantity = quantity; 
    this.options = options;
}

shoppingCart = {
    itemCount: 0,
    totalPrice: 0,
    productIds: [],
    reloadCart: function(state, oprice, repeater, oid){    
        $('span#cartItemCount').html(this.itemCount); 
        $('span#cartTotal').html(this.totalPrice);                    
    }    
}        

function refreshCookies(obj, oid, procedure){     
    shoppingCart.itemCount = 0;
    shoppingCart.totalPrice = 0;
       
    var str = "{";  
    
    for(a in shoppingCart.productIds){
        if(shoppingCart.productIds.length == 1){
            str += "\"" + shoppingCart.productIds[a][0] + "\" : { \"quantity\" : " + shoppingCart.productIds[a][1] + ",  \"collectivePrice\" : " + shoppingCart.productIds[a][2] + ",  \"itemPrice\" : " + shoppingCart.productIds[a][3] + ", \"options\" : \"" + shoppingCart.productIds[a][4] + "\"}";                 
        }else{  
            if(a != (shoppingCart.productIds.length - 1)){
                str += "\"" + shoppingCart.productIds[a][0] + "\" : { \"quantity\" : " + shoppingCart.productIds[a][1] + ",  \"collectivePrice\" : " + shoppingCart.productIds[a][2] + ",  \"itemPrice\" : " + shoppingCart.productIds[a][3] + ", \"options\" : \"" + shoppingCart.productIds[a][4] + "\"}, ";   
            }else{          
                str += "\"" + shoppingCart.productIds[a][0] + "\" : { \"quantity\" : " + shoppingCart.productIds[a][1] + ",  \"collectivePrice\" : " + shoppingCart.productIds[a][2] + ",  \"itemPrice\" : " + shoppingCart.productIds[a][3] + ", \"options\" : \"" + shoppingCart.productIds[a][4] + "\"}";   
            }
        }    
        
        if(isNaN(shoppingCart.productIds[a][1])){shoppingCart.productIds[a][1] = 0;}          
        if(isNaN(shoppingCart.productIds[a][2])){shoppingCart.productIds[a][2] = 0;}
            
        shoppingCart.itemCount += parseInt(shoppingCart.productIds[a][1]); 
        shoppingCart.totalPrice += parseInt(shoppingCart.productIds[a][2]); 
    }    
        
    str += "}";                                  
    
    if(!procedure){
        $('.loadingSign' + oid).show();     
        $('input#quantity' + oid).hide();
    }
    
    $.ajax({          
        type: 'POST',
        url: siteUrl + '/addProductToCookie.php',
        context: document.body,
        data: 'productQuantity=' + str,
        async: false,
        success: function(response){
            
            if(!procedure){
                shoppingCart.reloadCart();   
                $('#sessions').html(response);
                setTimeout(function(){
                    fakeLoad(obj, oid);
                }, 1000); 
            }else{
                window.location.reload();
            }
        },
        error: function(a, b, c){                                                                        
            window.location.reload();
            //alert("There has been an error: " + a + ", " + b + ", " + c + ". Please try again later...");
        }
    });              
}

function fakeLoad(obj, oid, currentColour){
    $('.loadingSign' + oid).hide();   
    $('input#quantity' + oid).show();
}

function addToCart(obj, oid, oslug, oprice, osku, ooptions, oext){ 
    var getQuantity = parseInt($('input#quantity' + oid).val());
    $('input#quantity' + oid).val(1);        
    var stop = false;
    
    if(shoppingCart.productIds.length == 0){   
        var insertMe = new Array('p' + oid + oext, getQuantity, (oprice * getQuantity), oprice, ooptions); 
        shoppingCart.productIds.push(insertMe);
    }else{            
        for(a in shoppingCart.productIds){
            if(!stop){
                if(shoppingCart.productIds[a][0] == 'p' + oid + oext){  
                    //var currentAmount = parseInt(shoppingCart.productIds[a][1]);
                    shoppingCart.productIds[a][1] += parseInt(getQuantity);    
                    shoppingCart.productIds[a][2] += parseInt(oprice * getQuantity); 
                    shoppingCart.productIds[a][3] = parseInt(oprice);  
                    shoppingCart.productIds[a][4] = ooptions;
                    stop = true;
                }
            }
        }
        if(!stop){ 
            shoppingCart.productIds.push(new Array('p' + oid + oext, getQuantity, (oprice * getQuantity), oprice, ooptions));  
        }         
    }
    
    refreshCookies(obj, oid);
}  

function displayUpdate(obj){
    $(obj).next().css('display', 'inline');
    $(obj).next().show();
}

function removeProduct(obj, oid){     
    
    $('#refreshing').show();
    $('#refreshing').height($('#content').height() - $('#title').height() + 30).html('<div id = "ajaxLoader2">Updating Basket...<br /><img src = "' + siteUrl + '/images/ajax-loader2.gif" /></div>');
    
    for(a in shoppingCart.productIds){
        if(shoppingCart.productIds[a][0] == oid){
            shoppingCart.productIds.splice(a, 1);
        }
        
        //updateCart();    
        
        refreshCookies(null, null, true);
        window.location.reload(); 
    } 
     
     
}

function numberFormat(total){  
    total = total+"";
    total = total.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
    return total; 
}

function updateCart(clicked){
    $('#refreshing').show();
    $('#refreshing').height($('#content').height() - $('#title').height() + 30).html('<div id = "ajaxLoader2">Updating Basket...<br /><img src = "' + siteUrl + '/images/ajax-loader2.gif" /></div>');
      
    var sumOfPrices = 0;                    
    for(a in shoppingCart.productIds){   
        var getQuantity = $('#quantity' + shoppingCart.productIds[a][0]).val();    
          
        if(getQuantity == 0){
            removeProduct('', shoppingCart.productIds[a][0]); 
            break;   
        }else{
            if(isNaN(getQuantity) || getQuantity == ""){
                getQuantity = 0;
            }                                                   
            shoppingCart.productIds[a][1] = getQuantity;
            shoppingCart.productIds[a][2] = shoppingCart.productIds[a][3] * getQuantity; 
        }     
    }       
     
    refreshCookies(null, null, true);
    sumOfPrices = 0;
    vatAdded = 0;  
}

function validate(obj, form){
    switch(form){
        case 'quantity':
                var quantity = $(obj).val();
                var pattern = /\D/;   
                if(pattern.test(quantity)){
                    $(obj).val('1');
                }        
                if(quantity == ""){
                    $(obj).val('1');
                }                   
            break;
    }
}

function galleryLaunch(state, obj){
    switch(state){
        case true:
            $('.tabLeftContent').hide(); 
            break;
        case false: 
            var related = $(obj).attr('related'); 
            if(related != 'five'){
                $('.tabLeftContent').show();
            }
            break;            
    }
}     
