/**
 * Master Javascript
 *
 * @copyright   2010 SimonRichards
 * @category    Laminex CMS
 * @package     Formica
 * @version     $Id$
 */

function implode(glue, pieces) {
    return (( pieces instanceof Array ) ? pieces.join ( glue ) : pieces);
}

function updateCart(target)
{
    if (target == undefined) {
        target = "#cart-content";
    }

    $.post(
        'site.php',
        {
            'data[action]': 'cart',
            'action': 'cart'
        },
        function(data) {
            $(target).html(data);
        }
        );
}

(function($) {
    var cache = [];
    $.preload = function() {
        var argLength = arguments.length;
        for (var i = argLength; i--;) {
            var cacheImage = document.createElement('img');
            cacheImage.src = arguments[i];
            cache.push(cacheImage);
        }
    }
})(jQuery);

$("#cart-title").live("click", function() {
    $("#cart-content").toggle();
});

function updateList() {
    var id = $("#tech-info-menu a.current").attr("rel");
    var list = data[id];
    html = "";
    count = 0;
    $.each(list, function(index, row) {
        count++;
        if (count % 2) {
            html = html +
                   "<li><a class=\"grey\" href=\"javascript:void(0)\" onclick=\"LaunchTechPopUp('uploads/tech-info/" + row.pdf + "')\">" + row.title + "<span class=\"download\"><u>Download PDF</u> &gt;</span></a></li>";
        } else {
            html = html +
                   "<li><a href=\"javascript:void(0)\" onclick=\"LaunchTechPopUp('uploads/tech-info/" + row.pdf + "')\">" + row.title + "<span class=\"download\"><u>Download PDF</u> &gt;</span></a></li>";
        }

    });
    $("#tech-info-list").html(html);
}

function thisMovie(movieName) {
    if (navigator.appName.indexOf("Microsoft") != -1) {
        return window[movieName];
    } else {
        return document[movieName];
    }
}

function send() {
    thisMovie("kitchen").printkitchen();
}

function sendback(value) {
    document.getElementById('kitchenid').value = value;
    document.getElementById("send-to-friend").submit();
}

$(document).ready(function() {
    updateCart();
    bindButtons();
    $("a.external").attr("target", "_blank");

    // Cufon
    if ($(".cufon").length !== 0) {
        Cufon.replace(".cufon");
        Cufon.now();
    }

    $('#window-weekly-tip div.window-content').innerfade({
        animationtype: 'fade',
        speed: 750,
        timeout: 5000,
        type: 'random',
        containerheight: '120px'
    });
});

$(".fancy, #sender-design-image a").fancybox({
    'titlePosition'  : 'over',
    'transitionIn'   : 'elastic',
    'transitionOut'  : 'elastic'
});

$("a.innermap").fancybox({
    type: 'iframe',
    titleShow: false,
    width: 900,
    height: 480
});
$(".PromoLaunch, #PromoContainer a").fancybox({
	'width'				: '90%',
	'height'			: '90%',
	'autoScale'			: false,
	'transitionIn'		: 'none',
	'transitionOut'		: 'none',
	'type'				: 'iframe'
});
$(".TechPdf, #window-trade-links a").fancybox({
	'width'				: '90%',
	'height'			: '90%',
	'autoScale'			: false,
	'transitionIn'		: 'none',
	'transitionOut'		: 'none',
	'type'				: 'iframe'
});

$(".download-pdf-red, #news a").fancybox({
	'width'				: '90%',
	'height'			: '90%',
	'autoScale'			: false,
    'transitionIn'   : 'elastic',
    'transitionOut'  : 'elastic',
	'type'				: 'iframe'
});
$(".external, #gallery-download a").fancybox({
	'width'				: '90%',
	'height'			: '90%',
	'autoScale'			: false,
    'transitionIn'   : 'elastic',
    'transitionOut'  : 'elastic',
	'type'				: 'iframe'
});
$(".download-pdf-grey, #ColourRangeDownload a").fancybox({
	'width'				: '90%',
	'height'			: '90%',
	'autoScale'			: false,
    'transitionIn'   : 'elastic',
    'transitionOut'  : 'elastic',
	'type'				: 'iframe'
});

function LaunchTechPopUp(URL){
    $.fancybox({ 
	'width'				: '90%',
	'height'			: '90%',
	'autoScale'			: false,
    'transitionIn'   : 'elastic',
    'transitionOut'  : 'elastic',
	'href'           : URL,
	'type'				: 'iframe'
   });
}

if ($("#page-home")||("#page-index-temp").length > 0) {
   $("#home-hero img").bind("click", function() {
        var id = $(this).attr("src").substr(15, 1);
        if (id == 3) {
            id = 1;
        } else {
            id = parseFloat(id) + 1;
        }
        $(this).attr("src", "../uploads/home/static-home-" + id + ".jpg");
    });
	$('#HPslideShow1').css({ "visibility" : "visible" });
	$('#HPslideShowImg').css({ "visibility" : "visible" });
	$('#HPslideCategories').css({ "visibility" : "visible" });
}

if ($("#page-design-tool").length > 0) {
    $("#send-button").bind("click", function(){
        send();
    });

    swfobject.embedSWF("kitchen.swf", "kitchen", "951", "523", "9.0.0", "ui/install.swf", null, {wmode: "transparent"});

    $("#send-email a:first").bind("click", function() {
        var size = $(".receiver-detail").size();
        if (size === 5) {
            return false;
        }

        if (size === 4) {
            $("#send-email img:first").fadeTo("slow", 0.4);
        }

        var html = "<div class=\"receiver-detail\">" + $(".receiver-detail:first").html() + "<a href=\"javascript:void(0);\" class=\"delete-row\">Remove</a></div>";
        $(".receiver-detail:last").after(html);
        $(".receiver-detail:last").hide().slideDown();
    });

    $(".delete-row").live("click", function() {
        $(this).closest(".receiver-detail").slideUp(500, function() {
            $(this).remove();
            $("#send-email img:first").fadeTo("slow", 1);
        });
    });
}

// Gallery

if ($("#page-gallery").length > 0) {
    var totalTier = parseInt((parseInt(total) - 7) / 2);

    $("#gallery-next").click(function() {
        var target  = $("#gallery-sets .slider ul");
        var current = target.css("top");

        if (current == "auto") {
            current = 0;
        }

        if (parseInt(current) == 0) {
            $("#gallery-previus").animate({opacity: "1"});
        }

        var next = (parseInt(current) - 96) + "px";
        var nextTier = 0 - parseInt(next) / 96;

        if (nextTier > totalTier) {
            return false;
        }
        if (nextTier == totalTier) {
            $(this).animate({opacity: "0.3"});
        }

        target.animate({
            top: next
        });
    });

    $("#gallery-previus").click(function() {
        var target  = $("#gallery-sets .slider ul");
        var current = target.css("top");

        if (current == "auto") {
            current = 0;
        }

        if (parseInt(current) == 0) {
            return false;
        }

        var previus = (parseInt(current) + 96) + "px";
        var previusTier = 0 - parseInt(previus) / 96;

        if (previusTier <= totalTier) {
            $("#gallery-next").animate({opacity: "1"});
        }

        if (parseInt(previus) == 0) {
            $(this).animate({opacity: "0.3"});
        }

        target.animate({
            top: previus
        });
    });

    $.gallery = function(options) {
        var defaults = {
            list: "",
            imageFolder: "uploads/gallery/",
            setHtmlId: "gallery-sets",
            thumbHtmlId: "gallery-thumbs",
            heroHtmlId: "gallery-hero",
            descriptionHtmlId: "gallery-text",
            imageObjectPrefix: "image_"
        };

        var settings = $.extend({}, defaults, options);

        var setId = function() {
            return $("#" + settings.setHtmlId + " li.current").attr("id").substr(settings.setHtmlId.length);
        }

        var thumbId = function() {
            return $("#" + settings.thumbHtmlId + " li.current").attr("id").substr(settings.thumbHtmlId.length);
        }

        var imageKey = function(id) {
            return settings.imageObjectPrefix + id;
        }

        var hero = function(id, key) {
            return settings.list[id][imageKey(key)];
        }

        var updateHero = function() {
            $("#" + settings.heroHtmlId + " .slider").append('<img style="display: none" class="incoming" src="' + settings.imageFolder + hero(setId(), thumbId()) + '">');

            $("#" + settings.heroHtmlId + " .actual").fadeOut(750, function(){
                $(this).remove();
            });
            $("#" + settings.heroHtmlId + " .incoming").fadeIn(750, function() {
                $(this).removeClass("incoming").addClass("actual");
            });

            //$("#" + settings.heroHtmlId + " img").attr("src", settings.imageFolder + hero(setId(), thumbId()));
        }

        var updateDescription = function() {
            $("#" + settings.descriptionHtmlId).html(settings.list[setId()]["description"]);
        }

        var updatePDFDownload = function() {
            $("#gallery-download a").attr("href", "uploads/gallery/" + settings.list[setId()]["pdf"]);
        }

        var updateThumbs = function() {
            var thumb = settings.list[setId()];
            var thumb1 = thumb["image_1_thumb"];
            var thumb2 = thumb["image_2_thumb"];
            var thumb3 = thumb["image_3_thumb"];
            var alt = thumb["title"] + " #";

            $("#gallery-thumb-1 img").attr("src", settings.imageFolder + thumb1).attr("alt", alt + "1");
            $("#gallery-thumb-2 img").attr("src", settings.imageFolder + thumb2).attr("alt", alt + "2");
            $("#gallery-thumb-3 img").attr("src", settings.imageFolder + thumb3).attr("alt", alt + "3");
        }

        updateHero();
        updateDescription();
        updateThumbs();
        updatePDFDownload();
    };

    var galleryUpdate = function() {
        return $.gallery({list: list});
    };

    $("#gallery-thumbs li").live(
        "click",
        function () {
            if ($(this).hasClass("current")) {
                return true;
            }

            $("#gallery-thumbs li").removeClass("current");
            $(this).addClass("current");

            galleryUpdate();
        }
    );

    $("#gallery-sets li:not(.filler)").live(
        "click",
        function () {
            if ($(this).hasClass("current")) {
                return true;
            }

            $("#gallery-sets li").removeClass("current");
            $(this).addClass("current");

            $("#gallery-thumbs li").removeClass("current");
            $("#gallery-thumbs li:first").addClass("current");

            galleryUpdate();
        }
    );

    $.each(list, function(index, value) {
        $.preload("uploads/gallery/" + value.image_1);
        $.preload("uploads/gallery/" + value.image_2);
        $.preload("uploads/gallery/" + value.image_3);
    });
}

/*
if ($("#page-locator").length > 0) {
    $("select[name=type_id]").change(function() {
        var current = $(this).val();
        switch (current) {
            case '1':
                $(".dhtml").html("<br><b>TLG Display Showroom</b> - ﻿The Laminex Group Branches comprising of a product display showroom only and do not offer colour and product consultancy services.");
                break;
            case '4':
                $(".dhtml").html("<br><b>TLG Design Centre</b> - ﻿The Laminex Group Design Centre comprising of a comprehensive product display showroom and also offering a colour and product consultancy design service.");
                break;
            case '5':
                $(".dhtml").html("<br><b>Flooring stockists</b> - Flooring Retail Outlets run independently of The Laminex Group who stock and sell Formica Flooring products direct to consumers.");
                break;
            default:
                break;
        }
    });

    $(".submit-locator").click(function() {
        var type = $("select[name=type_id]").val();
        var postcode = $("input[name=postcode]").val();

        if (type == "0") {
            alert("Please select a store type.");
            return false;
        }

        if (postcode.length != 4) {
            alert("Please provide a valid postcode.");
            return false;
        }

        document.getElementById("search-form").submit();
    });
}


// Locator
if ($("#page-locator").length > 0) {
    $("#page-locator select").customSelect({
        width           : "296",
        height          : "28",
        innerBackground : "ui/arrow-select-large.gif"
    });

    $.locator({
        brandId   : '3',
        postcode  : postcode,
        typeId    : typeId,
        listWidth : 940
    });
}
*/
if ($("#page-order").length > 0) {
    updateCart("#cart-review-list");

    $("#consumer, #trade").bind("click", function() {
        var value = $(this).val();
        if (value === "trade") {
            $("#swatch-size").slideDown();
        } else if ($("#swatch-size").is(":visible")) {
            $("#swatch-size").slideUp();
        }
    });
}

// Cart

$(".cart-remove").live(
    'click',
    function() {
        var id = $(this).attr("rel");
        var cookie  = $.cookie("swatches");
        var current = cookie.split(" ");
        var count   = current.length;
        var result  = new Array();
        var options = { path: '/', expires: 1 };

        for (var i = 0; i < count; i += 1) {
            if (current[i] != id && current[i] != "" && current[i] != null) {
                result[i] = $.trim(current[i]);
            }
        }
        cookie = implode(" ", result);
        cookie = $.trim(cookie.replace(/  /g, " "));

        if (cookie.length == 0) {
            $("#swatch-heading").hide();
        }

        $.cookie("swatches", cookie, options);

        $(".cart-item-" + id).hide();

        /**
         * Check total items
         */
        var cookieSwatch  = $.cookie("swatches");
        var cookieBrochure  = $.cookie("brochures");
        var totalSwatch = 0;
        if (cookieSwatch != null && cookieSwatch != "" && cookieSwatch != undefined) {
            totalSwatch = cookieSwatch.split(" ").length;
        }
        var totalBrochure = 0;
        if (cookieBrochure != null && cookieBrochure != "" && cookieBrochure != undefined) {
            totalBrochure = cookieBrochure.split(" ").length;
        }
        var total = parseFloat(totalSwatch) + parseFloat(totalBrochure);

        if (total == 0) {
            $("#cart-order").hide();
            $("#cart-empty").show();
        }
});

$(".brochure-remove").live(
    'click',
    function() {
        var id = $(this).attr("rel");
        var cookie  = $.cookie("brochures");
        var current = cookie.split(" ");
        var count   = current.length;
        var result  = new Array();
        var options = { path: '/', expires: 1 };

        for (var i = 0; i < count; i += 1) {
            if (current[i] != id && current[i] != "" && current[i] != null) {
                result[i] = $.trim(current[i]);
            }
        }
        cookie = implode(" ", result);
        cookie = $.trim(cookie.replace(/  /g, " "));

        if (cookie.length == 0) {
            $("#brochure-heading").hide();
        }

        $.cookie("brochures", cookie, options);

        $(".brochure-" + id).hide();

        /**
         * Check total items
         */
        var cookieSwatch  = $.cookie("swatches");
        var cookieBrochure  = $.cookie("brochures");
        var totalSwatch = 0;
        if (cookieSwatch != null && cookieSwatch != "" && cookieSwatch != undefined) {
            totalSwatch = cookieSwatch.split(" ").length;
        }
        var totalBrochure = 0;
        if (cookieBrochure != null && cookieBrochure != "" && cookieBrochure != undefined) {
            totalBrochure = cookieBrochure.split(" ").length;
        }
        var total = parseFloat(totalSwatch) + parseFloat(totalBrochure);

        if (total == 0) {
            $("#cart-order").hide();
            $("#cart-empty").show();
        }
});

if ($("#page-tech-info").length > 0) {
    $(document).ready(function() {
        $("#tech-info-menu a[rel=" + target + "]").addClass("current");
        updateList();
    });

    $("#tech-info-menu a").live("click", function() {
        $("#tech-info-menu a").removeClass("current");
        $(this).addClass("current");
        updateList();
    });
}
function MM_goToURL() { //v3.0
  var i, args=MM_goToURL.arguments; document.MM_returnValue = false;
  for (i=0; i<(args.length-1); i+=2) eval(args[i]+".location='"+args[i+1]+"'");
}
function navigate(str){
	MM_goToURL('parent',str);return document.MM_returnValue
}
function navigate_external(str){
	MM_openBrWindow(str,'','top=0,left=0,width=1024,height=768,scrollbars=yes,resizable=yes,status=yes')
}
function MM_openBrWindow(theURL,winName,features) { //v2.0
  popupwindow=window.open(theURL,winName,features);
}

function gotoadmin(){
	MM_goToURL('parent','http://www.tlgcms.co.nz/Administration/Login.php?site=Formica');return document.MM_returnValue
}

