var x_offset = 0;
var y_offset = 0;
var z_index = 10;


$(document).ready(function(){
	//init_design();
	init_master();
	init_login();
	init_tree();
	
	if (/WebKit/i.test(navigator.userAgent)) {/* And solution for safari */
		var _timer = setInterval(function() {
			if (/complete/.test(document.readyState)) {
				clearInterval(_timer);
				init_design(); // call the onload handler
				init();
			}
		}, 10);
	}
	else{/* Solution for all browsers exept safari */
		$(window).load(
			function(){
				init_design();
				init();
			}
		);
	}
	
	

});

function init_master(){
	$('.window_close').unbind();
	$('.post_href').unbind();
	$('.info_window').unbind();
	$('.inner_main').unbind();
	$('#view_cart_href').unbind();
	/*  
	 * function that reads the href of a <a> and performs a ajax request:
	 * href should be on format:
	 * url;target;parameters [name:value,];callback
	 * Example:
	 * 		module=admin&c=product_form;#accessory_list;product_nr:1,accessory_product_nr:2,action:accessory,sub_action:unbind_product 
	 */	
	$('.post_href').one('click', function(){
		var data = this.href;
		post_href_ajax_call(data);
		return false;
	});
	
	$('.info_window').bind('click',
		function(){
			var window_id = new_window();
			var url = this.href;
			var data = url.split(',');
			var window = $('#' + window_id);
			var content = $('#' + window_id + ' .content');
					 
			$.post(data[0],
				function(data2){
					content.html(data2);
					if(data[1] > 0){
						var width = data[1];
					}
					else{
						var width = (content.width() + 40);
					}
				
					if(data[2] > 0){
						var height = data[2];	
					}
					else{
						var height = (content.height() + 60);
					}

					content.width(parseInt(width));
					content.height(parseInt(height));
					window.height(parseInt(height) + 25);
					window.width(parseInt(width));		
				}
			);
			return false;
		}
	)
	
	/* Event handler 
	 * ?module=shop&c=view_product_family 
	 */
	 
	 $('.window_close').one('click',
		function(event) {
			var window = $(this).parents().filter('.window');
			var content = window.children().filter('.content');			
			window.slideUp('medium', 
				function(){
					content.html('');
					window.remove();
				}
			);
			return false;	
		}
	);
	$('#view_cart_href').bind('click',
		function(event){
			var window_id = new_window("view_cart_window", 400, 600, "Kundkorg");
			$('#view_cart_window_content').html('<p id="load_configurator_process"><img src="include/images/large_load_indicator.gif"><br/>Laddar varukorgen...</p>');
			var url = this.href;
			$.post(url + "&ajax=1", function(data){
				$('#view_cart_window_content').html(data);
				init_view_cart();
				//init_master();
				init_master();
				//eval(callback);
			});
			return false;
		}
	);

	return true; 
}

function redraw_panel(cart_sum, nr_of_items){
	if(cart_sum != undefined){
		$('#panel_cart_sum').html(cart_sum);
		$('#panel_cart_nr_of_items').html(nr_of_items);
		init_master();
	}
	else{
		$.post('?module=main&c=site_components&ajax=1', {action:'draw_cart_panel'}, 
				function(data){
						$("#cart_panel").html(data);
						init_master();		
				}
		);
	}
	return true;		
}

function init_design(){
	$(document).ready(function(){
		/* First make sure that leftpanel and main reachs all the way down to the footer 
		 * This could be done with css, but firefox wont display that correctly when using any of the doctypes
		 * Css solution works in IE 6 & IE7
	 */
		var wrapper = $("#wrapper");	
		var left_panel = $("#left_panel");
		var main = $("#main");
		var inner_main = $("#inner_main");
		
		/* if inner main has grown though to dynamic content, make sure so that main are large enouth...+10px */
		if(inner_main.height() > main.height()){
			main.css("height", inner_main.height() + 10);
		}
		
		var height = main.height();
		if(height < 600){
			height = 600;
			main.css("height",height);
		}
		left_panel.css("height", height);
		wrapper.css("height",height);
		$(".expand_on_load").css("height", height);
		$("#left_panel_bottom_container").css("visibility" ,"visible");
		return true;
	});
}

function init_login(target){
	$('#login_customer_form').unbind();
	$('#customer_form').unbind();
	$('#logout_href').unbind();	
	
	$('#login_customer_form').ajaxForm({success: 
			function(data){
				data = data.split('¤');
				if(data[0] == 1){
					redirect(data[1]);			
				}
				else{
					$(target).html(data[1]);
					eval(data[2]);
					init_login("'"+target+"'");
				}
			}
	});
	$('#customer_form').ajaxForm({success: 
			function(data){
				data = data.split('¤');
				if(data[0] == 1){
					redirect(data[1]);			
				}
				else{
					$(target).html(data[1]);
					eval(data[2]);
					init_login("'"+target+"'");
				}
			}
	});
	
	$('#logout_href').one('click',
		function() {
			$.post("?module=shop&c=customer_manager&ajax=1", {action: 'logout'}, 
				function(data){
					$('#inner_main').html(data);
					redraw_panel();
					init_design();
					init_login('#inner_main');			
				}
			);
			return false;
		}
	);
	
	
	
}

function init_tree(){
	/* Bind toggle to Link on click */
	$('.toggle_link').bind('click',
		function() {
			//$('.toggle_link').not(this).removeClass('selected');
			$(this).parent().parent().children().filter('div.toggle_container').toggle();
			var link_image = $(this).children().filter('.toggle_image');
			var image_array = link_image.attr('src').split("_");
			
			//if(image_array[2] == 'include/images/tree_2_expanded.gif'){
			if(image_array[2] == 'expanded.gif'){
				link_image.attr('src',image_array[0] + '_' + image_array[1] + '_collapsed.gif');
			}
			else if(image_array[2] == 'collapsed.gif'){
				link_image.attr('src',image_array[0] + '_' + image_array[1] + '_expanded.gif');
			}
			//document.write(image_array[0] + '_' + image_array[1] + '_expanded.gif');
			//$('.toggle_link').removeClass('open');
			//$(this).parents('li').children().children().filter('.toggle_link').addClass('open');
			//$('.toggle_link').not($('.open')).click();			
			this.blur();	
			
			return false;
		}
	);
		
	/* colapse the menu */
	$('.toggle_link').not($('.selected').parents('li').children().children().filter('.toggle_link')).click();
}

function init_view_cart(){
	$('.view_configurator_href').unbind();
	$('.cart_amount').unbind();
	
	$('.view_configurator_href').bind('click',
		function(event) {
			var id = new_window("add_to_cart_window", 500, 500, "Visa/ändra produktens konfiguration");
			$('#' + id + ' .content').html('<p id="load_configurator_process"><img src="include/images/large_load_indicator.gif"><br/>Laddar konfiguratorn...</p>');
			var cart_index = $(this).attr('id');
			post_href_ajax_call("?module=shop&c=add_to_cart;"+id+"_content;cart_index:" + cart_index + ",action:reopen;view_configurator()");
			init_configurator();
			return false;	
		}
	);
	$('.cart_amount').keyup(
		function() {
			$('.cart_amount').unbind();
			var amount = $(this).val();
			var id = $(this).attr("id");
			$.post('?module=shop&c=manage_cart&ajax=1', {amount: amount, action: 'update_amount', id: id}, 
				function(data){
					data = data.split(';');
					$("#item_price_" + id).html(data[1]);
					$("#item_sum_" + id).html(data[2]);
					$("#order_list_sum").html(data[4]);
					redraw_panel(data[3] + ' ' + data[5], data[0]);
					init_view_cart();					
				}
			);
		}
	);
}


function draw_panel(){
	$.post("?module=main&c=site_components&ajax=1", {action: 'draw_panel'}, 
		function(data){
		$('#cart_panel').html(data);	
		}
	);	
}

function draw_cart(){
	$.post('?module=shop&c=manage_cart&ajax=1', 
		function(data){
			$('#view_cart_window_content').html(data);
			init_view_cart();
			init_master();
		}
	);
}

function post_href_ajax_call(data, callback){
	var data = data.split(';');
	var url = data[0];
	var target = data[1];
	var callback = data[3];
	
	data = data[2].split(',');
	var object = new Object();
	for(i=0; i<data.length; i++){
		var tmp = data[i].split(':');
		object[tmp[0]] = tmp[1];
	}
	
	$.post(url + "&ajax=1", object, function(data){
		$(target).html(data);
		init_master();
		init();
		eval(callback);
	});
	return false;
}

function new_window(id, height, width, window_title){
	if(typeof window_title === "undefined"){
		var window_title = "emmagjort"
	}
	else{
		var window_title = "emmagjort - " + window_title;
	}

	/* if no id create a new id */	
	if(typeof id == "undefined"){ 
		var date = new Date;
		var id = date.getTime();
	}
	
	var scroll_x,scroll_y;
	if (self.pageYOffset) // all except Explorer
	{
		scroll_x = self.pageXOffset;
		scroll_y = self.pageYOffset;
	}
	else if (document.documentElement && document.documentElement.scrollTop)
	{	// Explorer 6 Strict
		scroll_x = document.documentElement.scrollLeft;
		scroll_y = document.documentElement.scrollTop;
	}
	else if (document.body) // all other Explorers
	{
		scroll_x = document.body.scrollLeft;
		scroll_y = document.body.scrollTop;
	}

	
	if(!$("#" + id).is("div")){
		$("#main").prepend('<div id="' + id + '" class="window"><div class="header"><a class="window_close left" title="Stäng fönster" href="#"><img src="include/images/window_close.gif" alt="Stäng fönster"></a><div class="header_text clearfix"></div></div><div class="content" id="' + id + '_content"></div></div>');
		var window = $("#" + id);
		var content = window.children().filter('.content');
		var title_bar = $("#" + id + ' .header_text');
	
				
		window.hide();
		
		x_offset += 10;
		y_offset += 10;
		z_index += 1;
		
		/* position:absolute;z-index:10;
		left:expression((this.offsetParent.clientWidth/2)-(this.clientWidth/2)+this.offsetParent.scrollLeft);
		top:expression((this.offsetParent.clientHeight/2)-(this.clientHeight/2)+this.offsetParent.scrollTop);">Please
			*/	
		if(typeof height === "undefined"){
			height = "300px";
		}
		
		if(typeof width === "undefined"){
			width = "auto";
		}		

		window.css('left', x_offset);
		window.css('top', scroll_y + y_offset);
		window.css('z-index', z_index);		
		window.css('width', width);
		window.css('height', height);

		content.css('width', width);
		content.css('height', height);
		
		window.Draggable( 
        	{ 
        	    zIndex:    20, 
        	    ghosting:false, 
        	    opacity: 0.7, 
        	    handle:    '.header_text' 
        	}
		);
		title_bar.html(window_title);
		window.slideDown('medium');
	}else{
		var window = $("#" + id);
		var content = window.children().filter('.content');
		var title_bar = $("#" + id + ' .header_text');
		title_bar.html(window_title);
		window.css('top', scroll_y + y_offset);
		window.html();
		window.show();
	}
		//window.show();
	//animate({height:'show',width:'show'}, 'slow'); 
	init_master();
	return id;
}

function form_submit(id){
	$('#' + id).submit();
}

function bind_form(form_id, target, success){
	$(document).ready(
		function(){
			if(success == ""){
				success = "init_design";
			}
			$(form_id).unbind();
			$(form_id).ajaxForm({target: target, success: success});
		}
		
	);
	
}
//jQuery.noConflict();
/*
browserHistory = new historyStack("browserHistory", "");
browserHistory.onBrowserAddressChanged = function(){
	redirect(browserHistory.removeHash(document.location.hash));
	return true;
};

*/
/**
 * Redirect the browser, this function is called from redirect in functions.php 
 * @param string url Location to redirect to
 */
function redirect(url){
	//location.href=url;
	//location.reload();
	window.location.href=url;
	//window.location.href.assign(url)
}

function reload(){
	redirect(window.location.href);
}

function view_box(id, message, type) {
	//$(document).ready(function(){
		$('#' + id).addClass(type);
		$('#' + id).html(message);
		$('#' + id).show();
	//});
		init_design();
}

/* Creates a div of the same dimensions as the elemetn identified by "element_to_blackout". 
 * The div holds a ajax process animation
 */
function ajax_show_process(element_to_blackout,fill_parent){
	var box = $(element_to_blackout);
	var content = box.innerHTML;
	var dimensions = box.getDimensions();
    	
	box.update('<div id="ajax_processing" style="display:none"></div>'+content);

	var ajax_box = $('ajax_processing');
	var width = dimensions.width+"px";
	var height = dimensions.height+"px";
	
	if(fill_parent == true){
		height = box.up(1).getHeight()+"px";
	}
	ajax_box.setStyle({
		width:width,
		height:height
	});

	ajax_box.show(ajax_box);
}

/* http://www.arraystudio.com/as-workshop/disable-form-submit-on-enter-keypress.html */
function disableEnterKey(e)
{
     var key;
     if(window.event)
          key = window.event.keyCode;     //IE
     else
          key = e.which;     //firefox

     if(key == 13)
          return false;
     else
          return true;
}

function insert_to_history(url){
	browserHistory.put(url);
}

/* Makes it possible to restrict a textarea with a maxlength */
function imposeMaxLength(Object, event, MaxLen){
  if(Object.value.length == MaxLen && event.keyCode != 8)
  	return false;
  else
  	return true;
}

function open_real_popup(href, title, width, height){
	window.open(href, title, 'width='+width+',height='+height+',scrollbars=yes');
}