// requestAnimationFrame() shim by Paul Irish
// http://paulirish.com/2011/requestanimationframe-for-smart-animating/
window.requestAnimFrame = (function() {
    return  window.requestAnimationFrame   || 
    window.webkitRequestAnimationFrame || 
    window.mozRequestAnimationFrame    || 
    window.oRequestAnimationFrame      || 
    window.msRequestAnimationFrame     || 
    function(/* function */ callback, /* DOMElement */ element){
        window.setTimeout(callback, 1000 / 60);
    };
})();

window.requestInterval = function(fn, delay) {
    if( !window.requestAnimationFrame     && 
        !window.webkitRequestAnimationFrame && 
        !window.mozRequestAnimationFrame    && 
        !window.oRequestAnimationFrame      && 
        !window.msRequestAnimationFrame)
        return window.setInterval(fn, delay);
    var start = new Date().getTime(),
    handle = new Object();
    function loop() {
        var current = new Date().getTime(),
        delta = current - start;
        if(delta >= delay) {
            fn.call();
            start = new Date().getTime();
        }
        handle.value = requestAnimFrame(loop);
    };
    handle.value = requestAnimFrame(loop);
    return handle;
}

/**
 * Behaves the same as clearInterval except uses cancelRequestAnimationFrame() where possible for better performance
 * @param {int|object} fn The callback function
 */
window.clearRequestInterval = function(handle) {
    window.cancelAnimationFrame ? window.cancelAnimationFrame(handle.value) :
    window.webkitCancelRequestAnimationFrame ? window.webkitCancelRequestAnimationFrame(handle.value)	:
    window.mozCancelRequestAnimationFrame ? window.mozCancelRequestAnimationFrame(handle.value) :
    window.oCancelRequestAnimationFrame	? window.oCancelRequestAnimationFrame(handle.value) :
    window.msCancelRequestAnimationFrame ? msCancelRequestAnimationFrame(handle.value) :
    clearInterval(handle);
};

window.requestTimeout = function(fn, delay) {
    if( !window.requestAnimationFrame      	&& 
        !window.webkitRequestAnimationFrame && 
        !window.mozRequestAnimationFrame    && 
        !window.oRequestAnimationFrame      && 
        !window.msRequestAnimationFrame)
        return window.setTimeout(fn, delay);
			
    var start = new Date().getTime(),
    handle = new Object();
		
    function loop(){
        var current = new Date().getTime(),
        delta = current - start;
			
        delta >= delay ? fn.call() : handle.value = requestAnimFrame(loop);
    };
	
    handle.value = requestAnimFrame(loop);
    return handle;
};

/**
 * Behaves the same as clearInterval except uses cancelRequestAnimationFrame() where possible for better performance
 * @param {int|object} fn The callback function
 */
window.clearRequestTimeout = function(handle) {
    window.cancelAnimationFrame ? window.cancelAnimationFrame(handle.value) :
    window.webkitCancelRequestAnimationFrame ? window.webkitCancelRequestAnimationFrame(handle.value)	:
    window.mozCancelRequestAnimationFrame ? window.mozCancelRequestAnimationFrame(handle.value) :
    window.oCancelRequestAnimationFrame	? window.oCancelRequestAnimationFrame(handle.value) :
    window.msCancelRequestAnimationFrame ? msCancelRequestAnimationFrame(handle.value) :
    clearTimeout(handle);
};

$(window).load(function(){
    $('#list_of_product').lavaLamp({
        autoReturn: false,
        autoResize:true
    });
})

$(document).ready(function() {
    
    var Shop = new shoppingCart('eshoprid');
    Shop.initialize();
    $.ajaxSetup({
        beforeSend: function() {
            $("#ajaxloader").overlay({
                mask: {},
                load: true
            });
        }
    });
    
    if (Shop.isEmpty()){
        $('#open_cart_button').css({
            'color':'#6e0804'
        });
        $('#open_cart_button').html(Shop.numberOfItems() + ' item(s) Total sum: ' + '&euro;' + Shop.calculateTotal());
        $('#cart_content').html(drawCartTable());
        $('#checkoutsubmit').removeAttr('disabled');
    } else {
        $('#checkoutsubmit').attr('disabled', 'disabled');
        $('#open_cart_button').html('your bag is empty');
        $('#cart_content').html(drawCartTable());
    }
    
    
    $('ul#group_menu_list').lavaLamp({
        target: 'li a',
        autoReturn: true,
        autoSize:true
    });
    
    // *************** callback *************
    $("#callback_button_en").click(function(){
        $("#callback_form_en").show( 'slow', function(){
            $('#callback_form_en').mask({
                color: null, 
                closeOnClick: false, 
                zIndex: 10, 
                opacity: 0.9
            });
        });
    });
    $("#callback_button_de").click(function(){
        $("#callback_form_de").show( 'slow', function(){
            $('#callback_form_de').mask({
                color: null, 
                closeOnClick: false, 
                zIndex: 10, 
                opacity: 0.9
            });
        });
    });
    $("#callback_button_es").click(function(){
        $("#callback_form_es").show( 'slow', function(){
            $('#callback_form_es').mask({
                color: null, 
                closeOnClick: false, 
                zIndex: 10, 
                opacity: 0.9
            });
        });
    });
    $('.sendcallrequest').click(function(){
        var s = $(this).closest('form').serialize();
        var o = $(this).closest('form');
        $.post('/modules/eshop/ajax.functions.php',{
            callback: s
        },
        function onSuccess(data){
            if (/^Enter/.test(data)){
                alert(data);
            } else {
                $('input', o).each(function(){
                    $(this).val('');
                });
                alert(data);
                $(o).closest('.callback_windows').hide();
                $.mask.close();
            }
        });
    });
    
    // *************** login ***************
    $('#login_button').click(function(){
        $('#login_box_hidden').show( 'slow', function(){
            $('#login_box_hidden').mask({
                color: null, 
                closeOnClick: false, 
                zIndex: 10, 
                opacity: 0.9
            });
        });
    });
    
    $('.close').click(function(){
        var p = $(this).parent();
        $.mask.close();
        $(p).hide('slow');
    });
    
    $('#open_cart_button').click(function(){
        $('#shopping_cart').show( 'slow', function(){
            $('#shopping_cart').mask({
                color: null, 
                closeOnClick: false, 
                zIndex: 10, 
                opacity: 0.9
            });
        });
    });
    
    $("ul#details_list").tabs("div#panels > div");
    $("ul#descriptions_list").tabs("div#descriptions > div", {
        onClick: function()
        {
            $('.dscription_lang').jScrollPane({
                showArrows: true, 
                arrowSize: 18
            });
        }
    });
    // menu
    //$('#top_menu_list').hover(function(){
    //    $('#top_menu_list ul').show();
    //    $('#top_menu_list ul').css('display', 'block');
    //});
    $('#top_menu_list').droppy({
        speed: 300
    });
    
    $('ul#top_menu_list').lavaLamp({
        autoSize:true
    });
    
    
    // cart functionality
    $('#add_to_cart').click(function(){
        var id = $('#prid').text();
        var nm = $('#prname').text();
        var pr = $('#prprice').text();
        var r = Shop.addToCart({
            prid: id, 
            name: nm, 
            price: pr
        });
        if (r){
            $('#open_cart_button').animate({
                'top': '30px'
            }, 400, function(){
                $('#open_cart_button').css({
                    'color':'#6e0804'
                });
                $('#open_cart_button').html(Shop.numberOfItems() + ' item(s) Total sum: '  + '&euro;' + Shop.calculateTotal());
                $('#cart_content').html(drawCartTable());
                $('#checkoutsubmit').removeAttr('disabled');
            });
            $('#open_cart_button').animate({
                'top' : '0'
            }, 400);
            $.add2cart('image_cart_wrapper','open_cart_button');
        }
    });
    
    $('.basketdelete').live('click', function(){
        var id = $(this).attr("id");
        var r = Shop.deleteFromCart(id);
        if (r){
            if (!Shop.isEmpty()){
                $('#checkoutsubmit').attr('disabled', 'disabled');
            }
            $('#open_cart_button').html(Shop.numberOfItems() + ' item(s) Total sum: '+ '&euro;' + Shop.calculateTotal() );
            $('#cart_content').html(drawCartTable());
        }
    });
    
    $('.basketqty').live('change', function() {
        var id = $(this).attr('id');
        var qty = $(this).attr('value');
        
        var r = Shop.qtyUpdate(id, qty);
        $('#open_cart_button').html(Shop.numberOfItems() + ' item(s) Total sum: '+ '&euro;' + Shop.calculateTotal() );
        $('#cart_content').html(drawCartTable());
    });
    
    $('#submitcreditcard').bind('click', function(){
        var f = $('#reciept').serialize();
        $.post('/modules/eshop/ajax.functions.php',{
            cc: f
        }, onSuccess);
        function onSuccess(data){
            if (data > 0){
                //Shop.makeCartEmpty();
                //$('#open_cart_button').html(Shop.numberOfItems() + ' item(s) Total sum: '+ '&euro;' + Shop.calculateTotal() );
                //$('#cart_content').html(drawCartTable());
                $('#submit4b').submit();
            } else {
                alert('ERROR!');
            }
        }
    });
    $('#submitpaypal').click(function(){
        var s = $('#formpaypal').serialize();
        $.post('/modules/eshop/ajax.functions.php',
        {
            paypal: s
        }, onSuccess 
        );
        function onSuccess(data){
            if (data > 0){
                //Shop.makeCartEmpty();
                //$('#open_cart_button').html(Shop.numberOfItems() + ' item(s) Total sum: '+ '&euro;' + Shop.calculateTotal() );
                //$('#cart_content').html(drawCartTable());
                $("#formpaypal input[name='custom']").val(data);
                $('#formpaypal').submit();
            } else {
                alert('ERROR!');
            }
        }

    });
    
    
    // ***************** registration ******************
    $('#forretailers').click(function(){
        $('#retailer input[type=hidden]').removeAttr('disabled');
        $('#login_form').slideToggle('800');
        $('#newsletter_subsr').hide();
        $('#signupretailers').slideToggle('800');
        $('#registration_choice').hide();
        
    });
    
    $('#formusicians').click(function(){
        $('#musician input[type=hidden]').removeAttr('disabled');
        $('#login_form').slideToggle('800');
        $('#registration_choice').hide();
    });
    
    $('#reglogin').click(function(){
        $('#login_box_hidden').show( 'slow', function(){
            if (Shop.isEmpty()){
                var expdat = new Date();
                var period = expdat.getTime() + 604800000;
                expdat.setTime(period);
                var cookiestring = 'checkout=true';
                cookiestring += '; expires=' + expdat.toGMTString() + "; path=/";
                document.cookie = cookiestring;
            }
            
            $('#login_box_hidden').mask({
                color: null, 
                closeOnClick: false, 
                zIndex: 10, 
                opacity: 0.9
            });
        });
    });
    $('#regcountries').live('change', function(){
        var t = $('#regcountries option:selected').attr('value');
        $('#regcity').next().hide('slow');
        $('#regcity').show('slow');
        $('#regcity').attr('disabled', 'disabled');
        $('#regregions').attr('disabled', 'disabled');
        $.post('/modules/eshop/ajax.functions.php',
        {
            country: t
        },
        onSuccess
        );
        function onSuccess(data){
            $('#regregions').html(data);
            $('#regregions').removeAttr('disabled');
        }
    });
    
    $('#regregions').bind('change', function(){
        var t = $('#regregions option:selected').attr('value');
        $('#regcity').next().hide('slow');
        $('#regcity').show('slow');
        $.post('/modules/eshop/ajax.functions.php',
        {
            regional: t
        },
        onSuccess
        );
        function onSuccess(data){
            $('#regcity').html(data);
            $('#regcity').removeAttr('disabled');
        }
    });
    
    $('#regcity').bind('change', function(){
        var t = $('#regcity option:selected').attr('value');
        //alert(t);
        if (t == 'not'){
            $('#regcity').next().removeAttr('disabled');
            $('#regcity').next().show('slow');
            $('#regcity').hide('slow');
        }
    });
    $('#registration_choice').lavaLamp({
        //        target: 'p',
        //        container: 'div',
        autoReturn: false,
        autoSize:true
    });
    
    $('#change_settings_toggle').bind('click', function(){
        $('#changesettingstable').fadeToggle("slow");
    });
    
    $('#view_purchases_toggle').bind('click', function(){
        $('#user_transactions').fadeToggle("slow");
    });
    
    // ****************** product details *****************
    
    $(".moreimages[rel]").overlay({
        mask: {}
    });
    $("#shpc_button[rel]").overlay({
        mask: {}
    });
    
    
    $("#horizontal_product_list").scrollable({
        mousewheel: true
    });
    
    $('#questionbutton').click(function(){
        var s = $('#questionform').serialize();
        $.post('/modules/eshop/ajax.functions.php',{
            question: s
        },
        function onSuccess(data){
            alert(data);
        }
        );
    //        alert(s);
    });
     
    var validUntil = new Date($('#validYear').text(),$('#validMonth').text()- 1,$('#validDate').text());
    //validUntil = new Date('Thu Jan 12 2012 17:03:00');
    //alert(validUntil);
    //validUntil.setSeconds(validUntil.getSeconds() + 10.5); 
    $('#spesialOfferCount').countdown({
        until: validUntil, 
        onExpiry: featuredExpiration, 
        timezone: +0
    });
    
    function featuredExpiration(){
        $('#makeUnfeatured form').submit();
    }
    //    $('#remaining_time').hide();
    requestInterval(function(){
        $('#remaining_time').fadeToggle();
    }, 1000);
    //    setTimeout(function(){
    //        $('#remaining_time').show();
    //        setInterval(function(){
    //            $("#remaining_time").toggle();
    //        },500)
    //    },3000);
    
    $(".lightbox").lightbox({
        fitToScreen: true,
        displayDownloadLink: false
    });
    
    //$('#testimonials blockquote').quovolver();
    $('.NewsSummary ul li').revolver(600, 4000);
    function tick(){
        var el = $('#testimonials blockquote').length;
        if (el > 1){
            $('#testimonials blockquote:first').slideUp('slow', function () {
                $(this).appendTo($('#testimonials')).slideDown('slow');
            });
        }
    }
    requestInterval(function(){
        tick()
    }, 5000);
    // ****************** helpers ******************
    function drawCartTable(){
        var c = Shop.returnCart();
        var table = '<table cellpadding=0 cellspacing=0 ><tr><th class="basketPrName ">Name</th><th>Qty</th><th>Price</th><th>Delete</th></tr>';
        for (var i = 0 ; i < c.length ; i++){
            table += '<tr><td class="basketname">' 
            + c[i]['name'] 
            + '</td><td class="basketqtytd" >'
            + '<input type="text" value="' 
            + c[i]['qty'] 
            + '" size="2" id="' 
            + c[i]['id'] 
            + '" class="basketqty" name="' 
            + c[i]['id'] 
            +'" />' 
            + '</td><td class="basketprice">&euro; ' 
            + c[i]['price'] 
            + '</td><td class="basketdeletetd" >' 
            + '<span id="' + c[i]['id'] + '" class="basketdelete" >&nbsp;&nbsp;</span>'
            + '<input type="hidden" name="price_' + c[i]['id'] +'" value="' + c[i]['price'] + '" /></td></tr>';
        }
        table += '<tr><td></td><td></td><td></td><td></td></tr>';
        table += '<tr><td id="baskettotallbl" colspan="2" >Total:&nbsp;&nbsp;&nbsp;</td><td id="baskettotalsum" colspan="2" >&euro; '+ Shop.calculateTotal() + '</td></tr>';
        table += '</table>';
        return table;
    }
});

$.extend({
    add2cart: function(source_id, target_id, callback) {
        var source = $('#' + source_id );
        var target = $('#' + target_id );
        var shadow = $('#' + source_id + '_shadow');
        if( !shadow.attr('id') ) {
            $('body').prepend('<div id="'+source.attr('id')+'_shadow" style="display: none; background-color: #ddd; border: solid 1px darkgray; position: static; top: 0px; z-index: 10000;">&nbsp;</div>');
            var shadow = $('#'+source.attr('id')+'_shadow');
        }
        if( !shadow ) {
            alert('Cannot create the shadow div');
        }
        shadow.width(source.css('width')).height(source.css('height')).css('top', source.offset().top).css('left', source.offset().left).css('opacity', 0.5).show();
        shadow.css('position', 'absolute');
        shadow.animate( {
            width: target.innerWidth(), 
            height: target.innerHeight(), 
            top: target.offset().top, 
            left: target.offset().left
        }, {
            duration: 700
        } ).animate( {
            opacity: 0
        }, {
            duration: 700, 
            complete: callback
        } );
        shadow.css('z-index', 0);
    }
});

$.fn.revolver = function(speed, delay) {
    if (!speed) speed = 500;
    if (!delay) delay = 6000;
    var quaSpd = (speed*4);
    if (quaSpd > (delay)) delay = quaSpd;
    var	quote = $(this),
    firstQuo = $(this).filter(':first'),
    lastQuo = $(this).filter(':last');
    var el = $(this).length;
    if (el > 1){
        $(this).hide();
        $(firstQuo).show();
        intID = requestInterval(function(){
            if($(lastQuo).is(':visible')) {
                var nextElem = $(firstQuo);
            } else {
                var nextElem = $(quote).filter(':visible').next();
            }
            $(quote).filter(':visible').fadeOut(speed);		
            if($(lastQuo).is(':visible')) {
                requestTimeout(function() {
                    $(firstQuo).fadeIn(speed*2);
                }, speed*2);
            } else {
                requestTimeout(function() {
                    $(nextElem).fadeIn(speed);
                }, speed*2);
            }
        }, delay);
    }
};

function shoppingCart(){
    var records = new Array();
    
    this.initialize = function(prefix) {
        var prefix = prefix || 'eshoprid';
        var exp = "(" + prefix +"\\d+)";
        var regular = new RegExp(exp);
        var cookies = document.cookie;
        var y = cookies.split(';');
        for (var i = 0 ; i < y.length ; i++){
            var n = y[i].split('=');
            if (regular.test(n[0]) && n[1] != ''){
                var v = decodeURIComponent(n[1]);
                var x = v.split('&');
                var o = new Object();
                o['id'] = n[0].replace(/(&nbsp;)+|\s+/g,'');
                for (var j = 0; j < x.length ; j++){
                    var k = x[j].split(':');
                    o[k[0]] = k[1];
                }
                records.push(o);
            }
        }
    };
    
    this.isEmpty = function() {
        var a = records.length;
        if (a){
            return true;
        } else {
            return false;
        }
    };
    
    this.length = function() {
        var i = records.length;
        return i;
    }
    
    this.numberOfItems = function(){
        var qty = new Number();
        if (records.length){
            for (var i = 0 ; i < records.length ; i ++){
                var q = Number(records[i]['qty']);
                qty = qty + q;
            }
            return qty;
        } else {
            return 0;
        }
        
    }
    
    this.calculateTotal = function(){
        var sum = new Number();
        if (records.length){
            for (var i = 0 ; i < records.length ; i ++){
                var q = Number(records[i]['qty']) * Number(records[i]['price']);
                sum = sum + q;
            }
            return sum;
        } else {
            return 0;
        }
    }
    
    this.addToCart = function(product){
        var prid = product.prid;
        prid = prid.replace(/(&nbsp;)+|\s+/g,'');
        var name = product.name;
        var price = product.price;
        var qty = product.qty || 1;
        for (var i = 0 ; i < records.length ; i++){
            if (records[i]['id'] == prid){
                qty = Number(records[i]['qty']) + Number(qty);
                records[i]['qty'] = qty;
            }
        }
        if (qty == 1){
            o = {
                id: prid, 
                name: name, 
                price: price, 
                qty: qty
            };
            records.push(o);
        }
        var expdat = new Date();
        var period = expdat.getTime() + 604800000;
        expdat.setTime(period);
        var cookiestring = prid + '=' + encodeURIComponent('name:' + name + '&price:' + price + '&qty:' + qty);
        cookiestring += '; expires=' + expdat.toGMTString();
        cookiestring += '; path=/'
        document.cookie = cookiestring;
        return true;
    }
    
    this.deleteFromCart = function(prid){
        prid = prid.replace(/(&nbsp;)+|\s+/g,'');
        var r = new Array();
        var cookiestring = prid + '=' + '; expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/';
        for (var i = 0 ; i < records.length ; i++){
            if (records[i]['id'] != prid){
                r.push(records[i]);
            }
        }
        records = r;
        document.cookie = cookiestring;
        return true;
    }
    
    this.makeCartEmpty = function(){
        for (var i = 0 ; i < records.length ; i++){
            var cookiestring = records[i]['id'] + '=' + "; expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/";
            document.cookie = cookiestring;
        }
        records = new Array();
        return true;
    }
    //to do = check qty for number
    this.qtyUpdate = function(prid, qty){
        if (Number(qty) < 1){
            var r = new Array();
            var cookiestring = prid + '=' + "; expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/";
            for (var i = 0 ; i < records.length ; i++){
                if (records[i]['id'] != prid){
                    r.push(records[i]);
                }
            }
            records = r;
            document.cookie = cookiestring;
            return false;
        } else {
            for (var i = 0 ; i < records.length ; i++){
                if (records[i]['id'] == prid){
                    if (records[i]['qty'] == qty){
                        return true;
                    } else {
                        records[i]['qty'] = qty;
                        var expdat = new Date();
                        var period = expdat.getTime() + 604800000;
                        expdat.setTime(period);
                        var cookiestring = records[i]['id'] + '=' + encodeURIComponent('name:' + records[i]['name'] + '&price:' + records[i]['price'] + '&qty:' + records[i]['qty']);
                        cookiestring += '; expires=' + expdat.toGMTString();
                        cookiestring += '; path=/'
                        document.cookie = cookiestring;
                        return true;
                    }
                }
            }
        }
    }
    
    this.returnCart = function(){
        return records;
    }
}

