

var email_regexp = /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.(aero|biz|cat|com|coop|edu|gov|info|int|jobs|mil|mobi|museum|name|net|org|travel|ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zr|zw)+$/;


        

 $(document).ready(function(){


    var base_address = null;

    if( document.getElementsByTagName ) {
        var elems = document.getElementsByTagName( 'base' );

        if( elems.length ) {
            base_address = elems[ 0 ].href;
        }
    }
    
    window.fbAsyncInit = function() {
        //Replace appId with your own
        FB.init({appId: '149560108456422', status: true, cookie: true,
               xfbml: true});
    };
    
    
    /*
     * Toggle sub menu in left sidebar
     */
     $('.sidebar_left_toggle_sub_menu').click(function() {
         $("#sub_menu").toggle();
     });
    
    
    /*
     * Add product to shopping cart
     * Reload cart
     */
    $('.cart_add_product').click(function() {
        
        //If function is called from product view page, there is also a custom quantity field
        if($("#product_view_quantity").val()) {
            var quantity = $("#product_view_quantity").val();
        } else {
            var quantity = 1;
        }
        
        var ajax_url = base_address + 'ajax/cart_add_product/' 
                                    + $(this).attr("product_article_number") + "/" 
                                    + quantity + "/" 
                                    +  $(this).attr("category_id");

        $.ajax({
            url: ajax_url,
            type: "POST",
            success: function(response) {
                $("#cart_container").html(response);
            }
        });
    });
    
    
    
    /*
     * Increase or decrease quantity of a product in cart
     * Reload cart
     */
    $('.cart_change_product_quantity').live('click', function() {
        
        if($(this).attr("action") == "decrease") {
            var ajax_url = base_address + 'ajax/cart_decrease_product_quantity/' + $(this).attr("product_article_number");
        } else {
            var ajax_url = base_address + 'ajax/cart_increase_product_quantity/' + $(this).attr("product_article_number");
        }

        $.ajax({
            url: ajax_url,
            type: "POST",
            success: function(response) {
                $("#cart_container").html(response);
            }
        });
    });
    
    
    
    /*
     * Perform an AJAX search and display search results
     */
    $("#main_search_field").keyup(function() {
        
        //Perform no search if search string is less than 4 characters
        if($(this).val().length < 4) {
            $('#main_search_results').html("");

        } else {
        
            var ajax_url            = base_address + "search/ajax";
            var data                = "search_string=" + $(this).val();
            
            $.post(ajax_url, data, function(response) {
                $("#main_search_results").bind("ajaxStart", function() {
                    $(this).html("Vänta...");
                }).bind("ajaxStop", function() {
                    $(this).html(response);
                });
            });
            
        }
    });
    
    
    /*
     * Toggle VAT for product prices
     */
    $(".toggle_vat").click(function() {        
        var ajax_url = base_address + "ajax/toggle_vat/" + $(this).val();
        
        $.ajax({
            url: ajax_url,
            type: "POST",
            success: function() {
                location.reload();
            }
        });
    });
    
    
    /*
     * Printer selector on main page: display dropdown list of printer types
     */
    $("#printer_selector_brands").change(function() {
   
        var ajax_url = base_address + "ajax/get_printer_types/" + $(this).val();
        
        $.ajax({
            url: ajax_url,
            type: "POST",
            success: function(response) {
                $("#printer_selector_types_container").html(response);
                $("#printer_selector_step1").removeClass('printer_selector_step_active');
                $("#printer_selector_step1").addClass('printer_selector_step_inactive');
                
                $("#printer_selector_step2").removeClass('printer_selector_step_inactive');
                $("#printer_selector_step2").addClass('printer_selector_step_active');
            }
        });  
        
    });
    
    /*
     * Printer selector on main page: display dropdown list of printers
     */
    $("#printer_selector_types").live('change', function() {
        
        var ajax_url = base_address + "ajax/get_printers/" + $(this).val();
        
        $.ajax({
            url: ajax_url,
            type: "POST",
            success: function(response) {
                $("#printer_selector_printers_container").html(response);
                
                $("#printer_selector_step2").removeClass('printer_selector_step_active');
                $("#printer_selector_step2").addClass('printer_selector_step_inactive');
                
                $("#printer_selector_step3").removeClass('printer_selector_step_inactive');
                $("#printer_selector_step3").addClass('printer_selector_step_active');
            }
        });  
        
    });
    
    /*
     * Printer selector on main page: redirect to chosen printer
     */
    $("#printer_selector_printers").live('change', function() {
        document.location.href= $(this).val();
    });
    
    
    /*
     * Account page: delete printer
     */
    $(".account_printer_delete").click(function() {
        if(confirm("Är du säker på att du vill ta bort denna skrivare från listan?")) {

            var ajax_url = base_address + "account/delete_printer/" + $(this).attr("category_id");
            
            $.ajax({
                url: ajax_url,
                type: "POST",
                success: function() {
                    location.reload();
                }
            });
            
        }
    });
    
    /*
     * Account page: send Klarna invoice
     */
    $(".account_klarna_send_invoice").click(function() {

        var ajax_url = base_address + "account/klarna_send_invoice/" + $(this).attr("order_id");
        
        $.ajax({
            url: ajax_url,
            type: "POST",
            success: function(response) {
                if(response == 1) {
                    alert("Fakturan har nu skickats till din e-postadress!");
                } else {
                    alert("Ett fel uppstod när fakturan skulle skickas till din e-postadress. Var god kontakta vår kundtjänst!");
                }
            }
        });

    });
    

    /*
    * Countdown for order deadline
    */

    var today = new Date();
    
    var day = today.getDay();
    if(day != 6 && day != 0) {

        var order_deadline = new Date(); 
        
        if(day == 5) {
            order_deadline.setHours(15,00,00,00);
        } else {
            order_deadline.setHours(17,00,00,00);
        }
        
        $("#countdown_time").countdown({
            date: order_deadline,
            htmlTemplate: "%{h}:%{m}:%{s}",
            onChange: function( event, timer ){
                $("#countdown").show();
            },
            onComplete: function( event ){
            
                $("#countdown").hide();
            },
            leadingZero: true
        });


    }
        
    $('#slides').slides({
        preload: true,
        play: 4000,
        pause: 2500,
        hoverPause: true
    });
    
    //Pause rotator and countdown when window is not in focus
    $(window).blur(function(){

        
        $("#countdown_time").countdown('pause');
        
    })
    
    //Resume rotator and countdown when window is in focus
    $(window).focus(function(){
  
        $("#countdown_time").countdown('resume');
    })


    /** ** ** ** ** ** ** **/
    /*
     */
    $('a.product_view_popup_link').click(function() {
        var popID = "product_view_popup";

        var popWidth = 500;
        var popHeight = 200;

        //Fade in the Popup and add close button
        $('#' + popID).html("");
        $('#' + popID).fadeIn().css({ 'width': Number( popWidth ), 'height' : Number(popHeight) });

        //Define margin for center alignment (vertical   horizontal) - we add 80px to the height/width to accomodate for the padding  and border width defined in the css
        var popMargTop = (popHeight + 80) / 2;
        var popMargLeft = (popWidth + 80) / 2;

        //Apply Margin to Popup
        $('#' + popID).css({
            'margin-top' : -popMargTop,
            'margin-left' : -popMargLeft
        });

        //Fade in Background
        $('body').append('<div id="product_view_popup_fade"></div>'); //Add the fade layer to bottom of the body tag.
        $('#product_view_popup_fade').css({'filter' : 'alpha(opacity=80)'}).fadeIn(); //Fade in the fade layer - .css({'filter' : 'alpha(opacity=80)'}) is used to fix the IE Bug on fading transparencies 


        var ajax_url = base_address + "ajax/product_view_popup";
        $.ajax({
            url: ajax_url,
            type: "POST",
            success: function(response) {
                $("#product_view_popup").html(response);
                $("#product_view_popup").prepend('<a href="#" class="product_view_popup_close"><img src="assets/image/checkout_popup_close.png" id="product_view_popup_close" title="Close Window" alt="Stäng" /></a>');
            }
        });
        
        return false;
    });

    //Close Popups and Fade Layer
    $('a.product_view_popup_close, #product_view_popup_fade').live('click', function() { //When clicking on the close or fade layer...
        $('#product_view_popup_fade , #product_view_popup').fadeOut(function() {
            $('#product_view_popup_fade, a.product_view_popup_close').remove();  //fade them both out
        });
        return false;
    });
    


    $("#product_view_popup_submit").live('click', function() {
        var ajax_url = base_address + "ajax/product_email";
        
        var sender_name     = $("#sender_name").val();
        var sender_email    = $("#sender_email").val();
        var recipient_name  = $("#recipient_name").val();
        var recipient_email = $("#recipient_email").val();
        
        if(sender_name != "" && sender_email != "" && recipient_name != "" && recipient_email != "") {
            
            var data = "product_article_number=" + $(".product_view_popup_link").attr("product_article_number") +
                        "&sender_name=" + sender_name +
                        "&sender_email=" + sender_email +
                        "&recipient_name=" + recipient_name +
                        "&recipient_email=" + recipient_email;
            
            $.post(ajax_url, data, function(response) {
              
                    if(response == 1) {
                        
                        $("#product_view_popup").html("<br><br><br>Ditt tips har skickats till " + recipient_email);
                    } else {
                        
                        $("#product_view_popup").html("<br><br><br>Ett fel uppstod när mailet skulle skickas. Vi beklagar detta och ber dig vår kundtjänst.");
                    }
                    $("#product_view_popup").prepend('<a href="#" class="product_view_popup_close"><img src="assets/image/checkout_popup_close.png" id="product_view_popup_close" title="Close Window" alt="Stäng" /></a>');
            });
        } else {
            alert("Var god och fyll i samtliga fält!");
        }
         
    });
    
    
    
    
    /*
     * Product view page: product rating function
     */
    $(document).ready(function() {
      $('#product_view_comment_form_rating_graphic').ratings(5).bind('ratingchanged', function(event, data) {
        $('#product_view_comment_form_rating').val(data.rating);
      });
    });
    
    
    /*
     * Product view page: display comment form
     */
    $("#product_view_comment_form_link").click(function() {
        $("#product_view_comment_form").show('fast', function() {
            $("#product_view_comment_form_link").hide();
        });
        
    });
    
    
    /*
     * Product view page: verify e-mail address in comment form and display message if it is not valid
     */
    $("#product_view_comment_form_email").blur(function() {
        var str = $(this).val();
        
        if(str.search(email_regexp) != -1) {
            $("#product_view_comment_form_email_message").html("");
        } else {
            $("#product_view_comment_form_email_message").html("Du måste ange en giltig e-postadress!");
        }        
        
    });
    
    
    /*
     * Product view page: save new product comment
     */
    $("#product_view_comment_add").click(function() {
        
        var rating = $("#product_view_comment_form_rating").val();
        
        if(rating < 1) {
            rating = 5;
        }
        
        if($("#product_view_comment_form_customer_id").val() == 0) {
            var str         = $("#product_view_comment_form_email").val();
            var validation  = str.search(email_regexp);
            var antispam    = 10;
        } else {
            var validation  = 1;
            var antispam    = 10;
        }
        
        if(validation != -1) {
            
            var ajax_url = base_address + "ajax/product_save_comment";
            
            var data =      "product_article_number="    + $("#product_view_comment_form_article_number").val()
                        +   "&customer_id="              + $("#product_view_comment_form_customer_id").val()
                        +   "&author_name="              + $("#product_view_comment_form_name").val()
                        +   "&customer_email="           + $("#product_view_comment_form_email").val()
                        +   "&contents="                 + $("#product_view_comment_form_contents").val()
                        +   "&antispam="                 + antispam
                        +   "&rating="                   + rating;
                        
            
            $.post(ajax_url, data, function(response) {
                    if(response == 1) {
                        $("#product_view_comment_form").hide('fast');
                        $("#product_view_comment_posted_message").show('fast');
                    } else if(response == "antispam_error") {
                        $("#product_view_comment_form_antispam_message").html("Du måste ange korrekt svar på frågan!");
                    } else {
                        alert("Ett fel uppstod när din kommentar skulle sparas. Vi beklagar detta och ber dig att istället höra av dig till vår kundtjänst med dina synpunkter.");
                    }
            });
        }

    });
    
    
    
    
    /** ** ** ** ** ** ** **/
    /*
     * Checkout functions 
     */
    //When you click on a link with class of poplight and the href starts with a # 
    $('a.checkout_popup_link').click(function() {
        var popID = "checkout_popup";

        var popWidth = 500;
        var popHeight = 500;

        //Fade in the Popup and add close button
        $('#' + popID).html("");
        $('#' + popID).fadeIn().css({ 'width': Number( popWidth ), 'height' : Number(popHeight) }).prepend('<a href="#" class="close"><img src="assets/image/checkout_popup_close.png" id="checkout_popup_close" title="Close Window" alt="Stäng" /></a>');

        //Define margin for center alignment (vertical   horizontal) - we add 80px to the height/width to accomodate for the padding  and border width defined in the css
        var popMargTop = (popHeight + 80) / 2;
        var popMargLeft = (popWidth + 80) / 2;

        //Apply Margin to Popup
        $('#' + popID).css({
            'margin-top' : -popMargTop,
            'margin-left' : -popMargLeft
        });

        //Fade in Background
        $('body').append('<div id="checkout_popup_fade"></div>'); //Add the fade layer to bottom of the body tag.
        $('#checkout_popup_fade').css({'filter' : 'alpha(opacity=80)'}).fadeIn(); //Fade in the fade layer - .css({'filter' : 'alpha(opacity=80)'}) is used to fix the IE Bug on fading transparencies 


        if($(this).attr('klarna')) {
            var iframe = document.createElement('iframe');
            iframe.id = 'iframe_klarna_invoice';
            iframe.frameBorder = 0;
            iframe.style.border = 0;
            iframe.style.width = '500px';
            iframe.style.height = '490px';		
            $("#checkout_popup").append(iframe);
            
            $("#iframe_klarna_invoice").attr("src", 'https://online.klarna.com/villkor.yaws?eid=10052&charge=20');
        } else {
            var iframe = document.createElement('iframe');
            iframe.id = 'iframe_terms';
            iframe.frameBorder = 0;
            iframe.style.border = 0;
            iframe.style.width = '500px';
            iframe.style.height = '490px';		
            $("#checkout_popup").append(iframe);
            
            $("#iframe_terms").attr("src", base_address + "checkout/view_terms");
        }
        return false;
    });

    //Close Popups and Fade Layer
    $('a.close, #checkout_popup_fade').live('click', function() { //When clicking on the close or fade layer...
        $('#checkout_popup_fade , #checkout_popup').fadeOut(function() {
            $('#checkout_popup_fade, a.close').remove();  //fade them both out
        });
        return false;
    });


    /* End of checkout functions */
    /** ** ** ** ** ** ** **/
    
    
    
    
    
    
    
    /** ** ** ** ** ** ** **/
    /*
     * ADMIN FUNCTIONS
     */

    /*
     * Delete stock order line
     */
    $(".stock_order_form_delete_line").live('click', function() {
        $('#line_' + $(this).attr('article_number')).remove();        
    });
    

    /*
     * Add stock order line
     */
    $(".stock_order_form_add_line").click(function() {
        
        if($("#add_quantity").val() < 1) {
            $("#add_quantity").val(1);
        }
        
        var ajax_url = base_address + "admin/product/stock_order_form_line/" + $("#add_article_number").val() + "/" + $("#add_quantity").val()
        
        $.ajax({
            url: ajax_url,
            type: "POST",
            success: function(response) {
                
                if(response == 0) {
                    alert("Artikelnumret är okänt. Kontrollera att du skrivit rätt!");
                } else {
                    $('#stock_order_form_table tr:last').after(response);
                    $("#add_article_number").val("");
                    $("#add_quantity").val("");
                }
            }
        });
        
        

    });


    /*
     * END OF ADMIN FUNCTIONS
     */
    /** ** ** ** ** ** ** **/
 });

