// The jQuery Address / AJAX functionality
var first_time = true;

// See if a json object contains a key
function has_key(val) {
    return val == undefined ? false : true;
}

function replace_page(data, old_content, new_content) {
    if (data.title =='Home') {
        title = 'IntriG Wainscoting'
    } else {
        title = data.title + ' - IntriG Wainscoting';
    }
    $.address.title(title);
    if (isIE) {
        old_content.replaceWith(new_content);
        new_content.show();
    } else {
        old_content.replaceWith(new_content);
        new_content.fadeIn();
    }
    $("#loading").fadeOut(400);
}

// Selects the proper link
function update_menus(clicked_url) {
    $("#menu > li > a").each(function() {
        var el = $(this);
        if (el.attr('href') == clicked_url) {
            el.parent().addClass('active-parent');
        } else el.parent().removeClass('active-parent');
    });
    $("#menu > li > ul > li > a").each(function() {
        var el = $(this);
        if (el.attr('href') == clicked_url) {
            el.addClass('active');
            el.parent().parent().parent().addClass('active-parent');
        } else el.removeClass('active');
    });
    $("#menu li li li a").each(function() {
        var el = $(this);
        if (el.attr('href') == clicked_url || el.attr('href') == clicked_url.replace(/\d+\//gi,'')) {
            el.addClass('active');
            el.parent().parent().prev().addClass('active');
            el.parent().parent().parent().parent().parent().addClass('active-parent');
        } else el.removeClass('active');
    });
    update_bookmark_link();
};

function update_bookmark_link() {
    $("#facebook-link").attr("href", "http://www.facebook.com/share.php?u=" + window.location.href);
    $("#twitter-link").attr("href", "http://twitter.com/?status=Share " + window.location.href);
    $("#delicious-link").attr("href", "http://del.icio.us/post?url=" + window.location.href);
    $("#stumbleupon-link").attr("href", "http://www.stumbleupon.com/submit?url=" + window.location.href);
    $("#mailfriend-link").attr("href", "/mail-to-friend/?url=" + window.location.href);
    $("#bookmark-link").attr("href", window.location.href);
}

function slide(){
    $('.slideshow :first-child').fadeOut(1000).next('img').fadeIn(1000).end().appendTo('.slideshow');
    var last_active = $('#home-menu li.active');
    last_active.removeClass('active');
    var next = last_active.next();
    if (next.length == 0) {
        next = $('#home-menu li:first-child');
    }
    next.addClass('active');
}

function after_load(data) {
    var video_link = $("#selected_gallery_photo").find("#gallery_video");
    if (video_link.length) {
        video_link.css({
            "top" : ($("#selected_gallery_photo img").height() / 2) - 50,
            "left" : ($("#selected_gallery_photo img").width() / 2) - 50
        });
    }

    if ($('#picker').length != 0) {
        $('#picker').farbtastic(function(color){
            if (color_selector == 'ac-panel') {
                $('#id_panel').val(color);
                $('#base-panel').css('background-color', color);
            } else if (color_selector == 'ac-cap') {
                $('#id_cap').val(color);
                $('#panel-cap-background').css('background-color', color);
                $('#panel-base-background').css('background-color', color);
            } else if (color_selector == 'ac-wall') {
                $('#id_wall').val(color);
                $('#wall').css('background-color', color);
            }
        });
        $('#picker-close,.farbtopclose').live('click', function(){
           $("#color-picker").hide();
           return false;
        });
        $('#color-picker').draggable({
            handle:"div#picker div.farbtopmove",
            opacity: 0.7,
            cursor: 'move'
        });
    }
    if (data.title == 'Home') {
        window.slideshow = setInterval("slide();", 5000);
    }
    if (data.title == 'Contact') {
        $('#id_info_from').trigger('change');
    }
    apply_fancybox();
    if ($('#gallery_photo_list .scrollbar').length) {
        $('#gallery_photo_list').tinyscrollbar({ axis:'x',sizethumb:'29'});
    }
    if ($(".scrollable").length) {
        $(".scrollable").scrollable();
    }

    // URL overrides
    $("#menu li a").not("#main_menu li li a").each(function() {
        var url = $(this).attr('href');
        if (url == '/wainscot' || url == '/wainscot/') $(this).attr('href', '/wainscot/design-style/panel-design-style/');
        if (url == '/wainscot/design-style' || url == '/wainscot/design-style/') $(this).attr('href', '/wainscot/design-style/panel-design-style/');
    });

    // Remove all "noscript" tags
    $("noscript").remove();
}

function apply_fancybox() {
    if ($(".fancybox").length) {
        $(".fancybox").fancybox({
            'transitionIn'	: 'elastic',
            'transitionOut'	: 'elastic',
            'speedIn'	    : 600,
            'speedOut'	    : 200,
            'overlayColor'	: '#000',
            'overlayOpacity': 0.7
        });
    }
    if ($("#mailfriend-link").length) {
        $("#mailfriend-link").fancybox({
            'autoDimensions': false,
            'transitionIn'	: 'elastic',
            'transitionOut'	: 'elastic',
            'speedIn'	    : 600,
            'speedOut'	    : 200,
            'overlayColor'	: '#000',
            'overlayOpacity': 0.7,
            'width'         : 335,
            'height'        : 285
        });
    }
}

function update_page(url_with_slash, data, old_content, new_content) {
    if (isIE) {
        update_menus(url_with_slash);
        replace_page(data, old_content, new_content);
        after_load(data);
        if (has_key(data.gal_prev) || has_key(data.gal_next)) {
            add_gallery_nav(data.gal_prev, data.gal_next);
        }
    } else {
        old_content.fadeOut(400, function() {
            update_menus(url_with_slash);
            replace_page(data, old_content, new_content);
            after_load(data);
            if (has_key(data.gal_prev) || has_key(data.gal_next)) {
                add_gallery_nav(data.gal_prev, data.gal_next);
            }
        });
    }
}

function add_gallery_nav(prev, next) {
    $("body").find(".gallery_nav").remove();
    var div = $("body").find("#selected_gallery_photo");
    var img = div.find("img");

    var video_link = div.find("#gallery_video");
    if (video_link.length) {
        video_link.css({
            "top" : (img.height() / 2) - 50,
            "left" : (img.width() / 2) - 50
        });
    }

    var prev_div = $("<div class='gallery_nav prev'></div>");
    var next_div = $("<div class='gallery_nav next'></div>");
    prev_div.css({"width" : img.width()/3, "height" : img.height()});
    next_div.css({"width" : img.width()/3, "height" : img.height(), "right" : div.width() - img.width()});
    var prev_lnk = $("<a href='" + prev + "' title='Prev'></a>");
    var next_lnk = $("<a href='" + next + "' title='Next'></a>");
    prev_lnk.css({"width" : img.width()/3, "height" : img.height()});
    next_lnk.css({"width" : img.width()/3, "height" : img.height()});
    var prev_img = $("<img src='/media/js/fancybox/fancy_nav_left.png' alt='Prev' title='Prev' />");
    var next_img = $("<img src='/media/js/fancybox/fancy_nav_right.png' alt='Next' title='Next' />");
    prev_img.css({"top" : (img.height()/2) - 15});
    next_img.css({"top" : (img.height()/2) - 15});

    prev_div.html(prev_lnk);
    next_div.html(next_lnk);
    prev_lnk.html(prev_img);
    next_lnk.html(next_img);
    if (prev) {
        var stop_scroll = $("#gallery_photo_list .viewport .overview a:last").index() - 3;
        var scroll_to = $("#gallery_photo_list .viewport .overview a[href=" + prev + "]").index();
        if (scroll_to > stop_scroll) { scroll_to = stop_scroll; }
        $("#gallery_photo_list .viewport .overview").css({"left" : -1 * (scroll_to * 90)});
        div.prepend(prev_div);
        jQuery.preLoadImages(prev, prev);
        $(document).unbind('keyup.GalleryLeft');
        $(document).bind('keyup.GalleryLeft', function(event) {
            if (event.keyCode == 37) { // left arrow key
                prev_lnk.trigger('click');
            }
        });
    }
    if (next) {
        div.prepend(next_div);
        jQuery.preLoadImages(next, next);
        $(document).unbind('keyup.GalleryRight');
        $(document).bind('keyup.GalleryRight', function(event) {
            if (event.keyCode == 39) { // right arrow key
                next_lnk.trigger('click');
            }
        });
    }
}

function load_page(url_to_use, url_with_slash) {
    clearInterval(window.slideshow);
    clearInterval(window.slideshow);
    $("#loading").show();
    $.get(url_to_use, function(data) {
        if (has_key(data.view)) {
            var old_content = $("body").find("#all_content");
            if (data.view == "design_style_detail") {
                if ($('.selected_design_style_content').length) {
                    $('.selected_design_style_content').fadeOut(400, function() {
                        $("#gallery-scroll .items div a div.selected").remove();
                        $("#gallery-scroll .items div a").each(function() {
                            var el = $(this);
                            if (el.attr('id').replace('design_style-', '') == data.design_style_id) {
                                el.prepend("<div class='selected'></div>");
                            }
                        });
                        $(this).replaceWith(data.content).hide().fadeIn();
                        apply_fancybox();
                    });
                    $("#loading").fadeOut(400);
                } else {
                    load_page(url_to_use + "?initial=true", url_with_slash);
                }
            }
            else if (data.view == 'gallery_photo') {
                if ($('#selected_gallery_photo').length) {
                    var new_url = $(data.new_photo).find('img').attr('src');
                    var old_url = $('#selected_gallery_photo img').attr('src');
                    if (old_url != new_url) {
                        $('#gallery_photo_list .overview a.active').removeClass('active');
                        $('#selected_gallery_photo img').animate({opacity:0}, 'fast', function() {
                            $(this).replaceWith(data.new_photo).fadeIn();
                            $('#gallery_photo_list .overview a#gallery_photo-'+data.this_id).addClass('active');
                            add_gallery_nav(data.prev, data.next);
                        });
                        $("#selected_photo_content").replaceWith(data.new_photo_content);
                        $('#selected_photo_detail').replaceWith(data.new_photo_detail);
                        if(has_key(data.gallery_video) && data.gallery_video != '') {
                            $("#gallery_video").attr('href', data.gallery_video)
                                .attr('title', $('#selected_gallery_photo').find('img').attr('title')).show();
                        } else { $("#gallery_video").hide(); }
                    }
                    $("#loading").fadeOut(400);
                } else {
                    load_page(url_to_use + "?initial=true", url_with_slash);
                }
            } else { // if (data.view == "feincms_page")
                var new_content = $(data.content);
                if (has_key(data.left_sidebar)) {
                    $('#additional_left_section').html(data.left_sidebar);
                } else {
                    $('#additional_left_section').html('');
                }
                update_page(url_with_slash, data, old_content, new_content)
            }
        }
    }, "json");
}

function update_pricing(data) {
    $('#total').html(data.total);
    if (data.shipping)
        $('#shipping').html(data.shipping);
    $('#photos').html(data.result);
}

$(function(){
    var loading = '<div id="loading">loading... please wait.</div>';
    $('body').prepend(loading);

    var jquery_address_selector = "a:not(#picker-close,#gallery-scroll .browse,#share-links,.nolink,.palette a,.texture a,#fancybox-right,#fancybox-left,#fancybox-close,[href^=http])";
    $.address.init(function(event) {
        // Initializes the plugin
        $(jquery_address_selector).address();
    }).change(function(event) {
        var url = $.address.state().replace(/^\/$/, '') + event.value;
        var url_with_slash = url;
        if (!(url).match(/\/$/)) url_with_slash += "/";
        var url_to_use = url_with_slash;

        // Loads and populates the page data
        if (first_time) {
            first_time = false;
            $("#all_content").hide();
            url_to_use += "?initial=true"
        }
        load_page(url_to_use, url_with_slash);
    });

    $("#logout-action").click(function(){
       $("#login-action").show();
       $(this).hide(); 
    });
    
    $("#login-action").submit(function(){
       $("#logout-action").show();
       $(this).hide(); 
    });

    // Pricing AJAX function
    $("#form-pricing").live('submit', function(e) {
        e.preventDefault();
        var action = $(this).attr('action');
        $.post(action, $(this).serialize(), update_pricing, "json");
    });
    $('#id_design_style').live(isIE?'click':'change', function() {
        calculate_prices($(this));
    });
    /*
    $('#id_stairway, #id_linear_feet').live('keyup', function() {
        calculate_prices($(this));
    });
    */
    
    // FAQ AJAX function
    $("#form-faq").live('submit', function(){
        var action = $(this).attr('action');
        $.post(action, $("#form-faq").serialize(), function(data){
            $('#middle-content').html(data);
        });
        return false; 
    });

    function calculate_prices(el) {
        var action = el.parents('form').attr('action');
        $.post(action, $("#form-pricing").serialize(), update_pricing, "json");
    }
});

// Preload images script
(function($) {
    var cache = [];
    // Arguments are image paths relative to the current page.
    $.preLoadImages = function() {
        var args_len = arguments.length;
        for (var i = args_len; i--;) {
            var cacheImage = document.createElement('img');
            cacheImage.src = arguments[i];
            cache.push(cacheImage);
        }
    }
})(jQuery)

