﻿//DOM ready init
jQuery.noConflict();
var $ = jQuery.noConflict();

jQuery(function() {
    if (document.all) jQuery("#countrySelector").hover(function() { jQuery(this).addClass('hover') }, function() { jQuery(this).removeClass('hover') })
    //Color palette Tooltip. todo: turn this into a jquery-plugin
    var timer;
    jQuery("#colorpalette")
	.append('<div id="colorpalette-zoom"><div id="colorpalette-detail"><span id="colorpalette-name"></span></div></div>')
	.hover(
		function() {
		    jQuery(this).mousemove(function(e) {
		        var jQuerytip = jQuery("#colorpalette-zoom");
		        var pos = { left: e.pageX + 20, top: e.pageY - 10 };
		        if (pos.top + jQuerytip.height() + 5 > jQuery(window).height() + jQuery(window).scrollTop()) pos.top = jQuery(window).height() + jQuery(window).scrollTop() - jQuerytip.height() - 5;
		        jQuerytip.css(pos);
		    });
		},
		function() { jQuery(this).unbind("mousemove"); }
	)
	.find("a").each(function() {
	    jQuery(this).hover(
			function() {
			    clearTimeout(timer);
			    var jQueryel = jQuery(this);
			    jQueryel.css("opacity", "0.5");
			    jQuery("#colorpalette-zoom").fadeIn(400);
			    jQuery("#colorpalette-detail").css("background", jQueryel.css("background")).show();

			    var colorname = jQueryel.attr("name");
			    jQuery("#colorpalette-name").text(colorname);
			},
			function() {
			    var jQueryel = jQuery(this);
			    jQueryel.css("opacity", "1");
			    timer = setTimeout(function() { jQuery("#colorpalette-zoom").animate({ "opacity": "hide" }, 200) }, 200)
			}
		);
	});

    function onAfter(curr, next, prev, opts) {
        var img = $('img', next);
        var pos = parseInt(img.attr("id").replace('img', ''));
        var tot = $('.carousel-holder img').length;

        var imgTag, imgSrc, imgTag2, imgSrc2;
        // next
        imgTag = $('#img' + (pos + 1));
        imgSrc = $('#inp' + (pos + 1)).attr('value');
        // previous
        if (pos == 1) {
            //console.log(tot);
            imgTag2 = $('#img' + tot);
            imgSrc2 = $('#inp' + tot).attr('value');
        }
        else {
            imgTag2 = $('#img' + (pos - 1));
            imgSrc2 = $('#inp' + (pos - 1)).attr('value');
        }
        if (imgTag.attr('src') == "") {
            imgTag.attr('src', imgSrc);
        }
        if (imgTag2.attr('src') == "") {
            imgTag2.attr('src', imgSrc2);
        }
        //console.log((pos - 1) + ">" + pos + ">" + (pos + 1))
    };


    //used for carousel from the campaign
    sec = jQuery('#secondsCarousel').val();
    jQuery('.slideshow').cycle({
        fx: 'fade', // choose your transition type, ex: fade, scrollUp, shuffle, etc...
        pause: 1,
        timeout: sec,
        next: '#carousel-next',
        prev: '#carousel-prev'
        ,
        after: onAfter
    });

});

function showIframe(id, url) {
    var element = document.getElementById(id);
    if (element) {
        if (id == "iFrameChecklist") {
            hideIFrame(document.getElementById('iFrameSendToFriend'));
        }
        if (id == "iFrameSendToFriend") {
            hideIFrame(document.getElementById('iFrameChecklist'));
        }

        if (element.style.display == 'none') {
            element.style.display = '';
            element.src = url;
        }
        else {
            element.style.display = "none";
        }
        return false;
    }
    return true;
}

function hideIFrame(element) {
    if (element) {
        element.style.display = 'none';
    }
}

/* Shows or hides the element with the right id, and hides all others with class msl-large */
function toggleVisibility(id) {
    var element = document.getElementById(id);
    if (element) {
        if (element.style.display == 'none') {
            jQuery('.msl-large').hide();
            element.style.display = '';
        }
        else {
            element.style.display = "none";
        }
    }
}

function selectedBrandChange(brandId) {
    location.href = self.location.pathname + brandId;
}

function DyrupChecklist() {
    this.items = {};
    this.itemInfo = {};

    this.Add = function(productId) {
        if (this.items[productId] == null) {
            this.items[productId] = 1;
            this.LoadProductInfo();
        } else {
            this.items[productId]++;
        }
        this.Save();
        return this;
    }

    this.Remove = function(productId) {
        if (this.items[productId] != null) {
            this.items[productId]--;
        }
        this.Save();
        return this;
    }

    this.RemoveAll = function(productId) {
        delete this.items[productId];
        delete this.itemInfo[productId];
        this.Save();
        return this;
    }

    this.Save = function() {
        jQuery.cookie('checklist', JSON.stringify(this.items), { expires: 7, path: '/' });
        return this;
    }

    this.Clear = function() {
        this.items = {};
        this.itemInfo = {};
        this.Save();
        return this;
    }

    this.Load = function() {
        var data = jQuery.cookie('checklist');
        if (data == null) {
            this.items = {};
        } else {
            this.items = JSON.parse(data);
        }
        return this;
    }

    this.LoadProductInfo = function() {
        var arr = [];
        jQuery.each(this.items, function(i) {
            arr.push(i);
        });
        jQuery.ajax({
            url: "/json/Checklist.ashx",
            data: { mode: "info", 'product': arr },
            success: function(data) {
                DyrupChecklist.Get().itemInfo = JSON.parse(data);
                DyrupChecklist.Get().UpdateList();
            }
        });
    }

    this.UpdateList = function() {
        jQuery("#checklist ul").empty();
        jQuery("#checklist > h3").text("Your memo contains {0} products".localize(this.items.length));
        jQuery.each(this.itemInfo, function(prod, info) {
            var checklist = DyrupChecklist.Get();
            var num = checklist.items[prod];
            var link = '<a href="#" onclick="DyrupChecklist.Get().Add(\'' + prod + '\').UpdateList(); return false">Up</a>';
            link += ' - <a href="#" onclick="DyrupChecklist.Get().Remove(\'' + prod + '\').UpdateList(); return false">Down</a>';
            link += ' - <a href="#" onclick="DyrupChecklist.Get().RemoveAll(\'' + prod + '\').UpdateList(); return false">' + "Remove".localize() + '</a>';
            jQuery("#checklist ul").append("<li><h3>" + info['Name'] + "</h3><p>" + "Quantity: {0}".localize(num) + "</p>" + link + "</li>");
        });
        return this;
    }
}

/* Singleton accessor */
DyrupChecklist.Get = function() {
    if (typeof this.obj == 'undefined') {
        this.obj = new DyrupChecklist();
        this.obj.Load();
    }
    return this.obj;
}

/*
Add localize() method to string

Borrowed from http://www.jspwiki.org/wiki/JavascriptLocalization
*/
String.prototype.localize = function() {
    var s = LocalizedStrings[this];
    if (!s) return ("§§§" + this + "§§§");
    for (var i = 0; i < arguments.length; i++) {
        s = s.replace("{" + i + "}", arguments[i]);
    }
    return s;
}

// Load check list
/*
jQuery("#checklist").ready(function() {

jQuery.ajax({
url: "/json/Checklist.ashx",
data: { mode: "i18n" },
success: function(data) {
LocalizedStrings = JSON.parse(data);               
}
});

DyrupChecklist.Get().LoadProductInfo();
});
*/

function inspSwapIt(bg, colorcard) {
    jQuery(".environment-image").attr("src", bg);
    jQuery(".environment-colors img").attr("src", colorcard);
}

function makeModal(windowName) {
    jQuery("#" + windowName + "").jqm().jqmShow();
}

jQuery(document).ready(function() {
    jQuery("#faq dd").hide();
    // On click animation
    jQuery("#faq dt").click(function() {
        jQuery("#faq dd:visible").slideUp(200).prev("dt").removeClass("open");
        var dd = jQuery(this).next("dd");
        if (dd.is(":hidden")) {
            dd.slideDown(200);
            jQuery(this).addClass("open");
        } else {
            dd.slideUp(200);
        }
        return false;
    }).css("cursor", "pointer");
});


/* Dump function */
function dump(arr, level) {
    var dumped_text = "";
    if (!level) level = 0;

    //The padding given at the beginning of the line.
    var level_padding = "";
    for (var j = 0; j < level + 1; j++) level_padding += "    ";

    if (typeof (arr) == 'object') { //Array/Hashes/Objects
        for (var item in arr) {
            var value = arr[item];

            if (typeof (value) == 'object') { //If it is an array,
                dumped_text += level_padding + "'" + item + "' ...\n";
                dumped_text += dump(value, level + 1);
            } else {
                dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
            }
        }
    } else { //Stings/Chars/Numbers etc.
        dumped_text = "===>" + arr + "<===(" + typeof (arr) + ")";
    }
    return dumped_text;
}

jQuery.fn.centerScreen = function(loaded) {
    var obj = this;
    if (!loaded) {
        obj.css('top', jQuery(window).height() / 2 - this.height() / 2);
        obj.css('left', jQuery(window).width() / 2 - this.width() / 2);
        jQuery(window).resize(function() { obj.centerScreen(!loaded); });
    } else {
        obj.stop();
        obj.animate({ top: jQuery(window).height() / 2 - this.height() / 2, left: jQuery(window).width() / 2 - this.width() / 2 }, 200, 'linear');
    }
}


jQuery(document).ready(function() {
    jQuery('iframe').centerScreen();

    // Set specific variable to represent all iframe tags.
    var iFrames = document.getElementsByTagName('iframe');

    // Resize heights.
    function iResize() {
        // Iterate through all iframes in the page.
        for (var i = 0, j = iFrames.length; i < j; i++) {
            // Set inline style to equal the body height of the iframed content.
            iFrames[i].style.height = iFrames[i].contentWindow.document.body.offsetHeight + 'px';
        }
    }

    // Check if browser is Safari or Opera.
    if (jQuery.browser.safari || jQuery.browser.opera) {
        // Start timer when loaded.
        jQuery('iframe').load(function() {
            setTimeout(iResize, 0);
        }
			);

        // Safari and Opera need a kick-start.
        for (var i = 0, j = iFrames.length; i < j; i++) {
            var iSource = iFrames[i].src;
            iFrames[i].src = '';
            iFrames[i].src = iSource;
        }
    }
    else {
        // For other good browsers.
        jQuery('iframe').load(function() {
            // Set inline style to equal the body height of the iframed content.
            this.style.height = this.contentWindow.document.body.offsetHeight + 'px';
        }
			);
    }

    if (jQuery('#topnav').height() > 20) {
        jQuery('#masthead').css('height', '100px');
    }

    if (jQuery('input[name=hasLeftMenu]').val() == 'No') {
        jQuery('#page').css('background', 'none');
    }
});

//Locate dealer
function initSearch(alt) {
    if (!alt) alt = "";
    var search = jQuery('#search_input').val();
    var brand = jQuery('#brand_input').val();
    var country = jQuery('#country_input').val();
    var distance = jQuery('#distance_input').val();
    window.location = "?search=" + encodeURIComponent(search) + "&brand=" + brand + "&alt=" + alt + "&country=" + country + "&distance=" + distance;
}

function showPYH(link) {
    window.open(link, 'Mal', 'scrollbars=1,width=750,height=750');
    return false;
}	
