﻿//DOM ready init
$(function(){
	if(document.all) $("#countrySelector").hover(function(){$(this).addClass('hover')}, function(){$(this).removeClass('hover')})
	//Color palette Tooltip. todo: turn this into a jquery-plugin
	var timer;
	$("#colorpalette")
	.append('<div id="colorpalette-zoom"><div id="colorpalette-detail"></div></div>')
	.hover(
		function(){
			$(this).mousemove(function(e){
				var $tip = $("#colorpalette-zoom");
				var pos = {left:e.pageX+20, top: e.pageY-10};
				if (pos.top+$tip.height()+5 > $(window).height()+$(window).scrollTop()) pos.top = $(window).height()+$(window).scrollTop()-$tip.height()-5;
				$tip.css(pos);
			});
		},
		function(){$(this).unbind("mousemove");}
	)
	.find("a").each(function(){
		$(this).hover(
			function(){
				clearTimeout(timer);					
				var $el = $(this);
				$el.css("opacity","0.5");
				$("#colorpalette-zoom").fadeIn(400);
				$("#colorpalette-detail").css("background",$el.css("background")).show();
			}, 
			function(){
				var $el = $(this);
				$el.css("opacity","1");
				timer = setTimeout(function(){$("#colorpalette-zoom").animate({"opacity":"hide"},200)},200)
			}
		);
	});
	
	
});

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';
	}
}

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() {
        $.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 = $.cookie('checklist');
        if (data == null) {
            this.items = {};
        } else {
            this.items = JSON.parse(data);
        }
        return this;
    }
    
    this.LoadProductInfo = function() {    
        var arr = [];
        $.each(this.items, function(i) {
            arr.push(i);
        });   
        $.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() {    
        $("#checklist ul").empty();
        $("#checklist > h3").text("Your memo contains {0} products".localize(this.items.length));
        $.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>';
            $("#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
/*
$("#checklist").ready(function() {

    $.ajax({
        url: "/json/Checklist.ashx",
        data: { mode: "i18n" },
        success: function(data) {
            LocalizedStrings = JSON.parse(data);               
        }
    });

    DyrupChecklist.Get().LoadProductInfo();
});
*/

function inspSwapIt(bg, colorcard) {
	$(".environment-image").attr("src",bg);
	$(".environment-colors img").attr("src", colorcard);
}

function makeModal(windowName)
{
  $("#"+windowName+"").jqm().jqmShow();
}

$(document).ready(function() {
    $("#faq dd").hide();
    // On click animation
    $("#faq dt").click(function() {
		$("#faq dd:visible").slideUp(200).prev("dt").removeClass("open");
        var dd = $(this).next("dd");
        if (dd.is(":hidden")) {
            dd.slideDown(200);
			$(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', $(window).height()/2- this.height()/2); 
                        obj.css('left', $(window).width()/2- this.width()/2); 
                        $(window).resize(function() { obj.centerScreen(!loaded); }); 
                } else { 
                        obj.stop(); 
                        obj.animate({ top: $(window).height()/2- this.height()/2, left: $(window).width()/2-this.width()/2}, 200, 'linear'); 
                } 
        } 


$(document).ready(function()
	{
		$('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 ($.browser.safari || $.browser.opera)
		{
			// Start timer when loaded.
			$('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.
			$('iframe').load(function()
				{
					// Set inline style to equal the body height of the iframed content.
					this.style.height = this.contentWindow.document.body.offsetHeight + 'px';
				}
			);
		}
	}
);

//Locate dealer
function initSearch(alt) {
        if(!alt) alt="";
        var search = $('#search_input').val();
        var brand = $('#brand_input').val();
        var country = $('#country_input').val();
        var distance = $('#distance_input').val();
        window.location = "?search=" + encodeURIComponent(search) + "&brand=" + brand + "&alt=" + alt + "&country=" + country + "&distance=" + distance;
}