/*
	var cache = {
		// If url is '' (no fragment), display this div's content.
		'': $('.bbq-default')
	};		
*/	
var last = null;

/*
var master = false;
function goGet()
{
	$.ajax({
		url: 'http://lan1/ny/remote.php?wait=34',
		cache : false,
		success: function(data) {
			var u = data.replace(/\|/g,'&');
			//$('.result').append(data).append('<br/>');
			ProcessURL(u);
			//alert('Load was performed.');
			if(data != 'exit')
				goGet();
		},
		error: function(XMLHttpRequest, textStatus, errorThrown)
		{
			$('.result').append(textStatus);
		}
	});
}
*/

var news; 
var currentNewsItem = 0;
var NewsRolerMouseOver = false;
var _shop = new Shop();

function AddTobasket(id)
{
	_shop.add(id);
}

function createCookie(n,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = n+"="+value+expires+"; path=/";
}

function readCookie(n) {
	var nameEQ = n + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(n) {
	createCookie(n,"",-1);
}

function setNewsItem(i)
{
	if(news == null)
		return;
	$('#newsrole').fadeOut(200, function(){
		$('#news-role-header').html(news[i].heading);
		//$('#news-role-text').html(news[i].text);
		if(news[i].image == '')
		{
			$('#newsrole img').hide();
		}
		else
		{
			// NEWS_IMG_PATH is set in index.php
			$('#newsrole img').attr('src',NEWS_IMG_PATH + news[i].image);
			$('#newsrole img').show();
		}
		$('#newsrole').attr('href','#newslist.php?id='+i);
		$('#newsrole').fadeIn(300);
		//$('#newsrole');
	}).effect("highlight", {}, 500);
}

function getNews()
{
	$.ajax({
		url: 'api/rest.php?q=/news&p=20',
		datatype: 'json',
		cache : false,
		success: function(data) {
			news = data;
			setNewsItem(currentNewsItem++);
		},
		error: function(XMLHttpRequest, textStatus, errorThrown)
		{
			$('#news-role-header').html(textStatus);
			$('.result').append(textStatus);
		}
	});
	
	$('#newsrole').mouseover(function(){ 
		NewsRolerMouseOver = true;
		$('#news-role-header').css('color','#ddaa00');
	});
	$('#newsrole').mouseleave(function(){
		NewsRolerMouseOver = false;
		$('#news-role-header').css('color','#000000');
	});
	
	window.setInterval(function() {
		if(NewsRolerMouseOver || news == null) return;
		if(currentNewsItem >= news.length)
		{
			currentNewsItem = 0;
		}
		 setNewsItem(currentNewsItem++);
	}, 7000);
}

function showMenu(menu)
{
	if(!menu) menu = 'home';
	var title = '';
	if(menu == 'home')
	{
		title = 'Home';
	}else{
		title = $('#mainmenu a[cath='+menu+'] span').text();
	}
	if(title == '')
	{
		$('#accordion').hide();
		$('#accordion-title').hide();
	}else{
		$('#accordion').show();
		$('#accordion-title').show();
	}
	$('#accordion-title').text(title);
	$('div[cath]').hide();
	$('div[cath='+menu+']').show();
	$('#mainmenu a').removeClass('ui-state-focus');
	$('#mainmenu a[cath='+menu+']').addClass('ui-state-focus');
}

//Called from main menu buttons

function viewMenu(menu)
{
	//showMenu(menu);

	url = "/#cath="+menu;
	
	// Use document.location so back button works.
	// The rest is handled in "hashchange" event handler 
	document.location = url;
	
}


$(document).ready(function () {
	// add click handler, plus signs and color to menu items with children
	$('a[class|="lev"] + div')
		.prev()
		.prepend('<div class="ui-icon ui-icon-triangle-1-e" style="margin-left:-14px; float: left; width:12px;">+</div>')
		.css('font-weight','bold')
		.toggle(function() {
			//alert('First handler for .toggle() called.');
			$(this).next('div').show('fast');
		}, function() {
			$(this).next('div').hide('fast');
		})
		.next('div').hide();
	$('div[cath]').hide();
	$('#mainmenu a').button();
	$('td.mainmenubuttons').css('background-color','white').css('border','0px');
	//$('#infocenter a').button();
	//$('#accordion').hide();
	$('#interest-list-widget').hide();
	 // Debug things
	/*
	$('#knapp').click(function(){
		goGet();
	});
	
	$('#master').click(function(){
		master = true;
	});
	*/
	
	// History handling
	$(window).bind( 'hashchange', function(e) {
		HandleChange();
	});

	/*
	$('form#search').bind('onSubmit', function(e){
		url = '#products.php?search='+$('input#searchtext').val();
		document.location = url;		
	});
	*/
	
	$('input#searchbutton').click(function(e){
		DoSearch();
	});

	$('div#il-trash').click(function(e){
		$('#interestlist').html('');
		$('#interest-list-widget').hide();
		$('div#il-mail').hide();
		$('div#il-trash').hide();
		if($.jStorage.storageAvailable())
		{
			$.jStorage.deleteKey("interest.list");
		}
		//eraseCookie("ITLIST");
	});
	
    $('.ui-icon').hover(

            function(){ $(this).addClass('icon-active'); }, 

            function(){ $(this).removeClass('icon-active'); }

        );

	
	$('div#il-mail').click(function(e){
		var prods = $('#interestlist div a');
		var s = '';
		var at = '@';
		var tron = 'tron';
		var l = prods.length-1;
		$.each(prods, function(i,v){
			s+=v.text;
			if(i<l) s+=", ";			
		});
		window.location = 'mailto:info'+at+'acou'+tron+'ic.se?subject=I am interested in:'+s+'&body=Please send me more info on the following products: '+s;
	});
	
	$.get('newslist.php', function(data) {
		$('#news').html(data);
	});

	try{
		if($.jStorage.storageAvailable())
		{
			//cookie = localStorage["ITLIST"];
			try{
				cookie = $.jStorage.get("interest.list", null);
			}catch(e){
				cookie = null;
			}
			if(cookie)
			{
				$('#interest-list-widget').show();
				$("#interestlist").html(Base64.decode(cookie));
				$('div#il-mail').show();
				$('div#il-trash').show();
			} else {
				$('div#il-mail').hide();
				$('div#il-trash').hide();
			}
		}
	}catch(e){
	}

	getNews();
	_shop.updateInfo();
	$(window).trigger( 'hashchange' );	
				
});

function HandleChange()
{
	// get url from browser
	var url = $.param.fragment();
	var query = $.deparam.querystring();
	//$("#test").append("change: '" + url + "'  link: '"+query.link+"'<br/>");
	if(url == '')
	{
		if(query.link)
		{
			anch = $('a[cath='+query.link+']');
			//anch = $('a[hrefa$='+query.link+']');
			url = $.param.fragment(anch.attr('href1'));
			//$("#test").append("url: " + url + ":" + anch.attr('href1')+"<br/>");
			//document.location = '/#'+$.param.fragment(anch.attr('href'));
			//$.param.querystring('/');
			if(url == '') {
				viewMenu(query.link);
				return;
			}
		} else if(query.pid){
			//anch = $('a[href~='+query.pid+']');
			url = 'products.php?pid='+query.pid;
		} else if(query.Index){
			//anch = $('a[href~='+query.pid+']');
			url = 'products.php?pid='+query.Index;
		} else {
			//url = 'home.php';
		}
	}
	//$("#test").append("change: '" + url + "': '"+query.link + "'<br/>");
	ProcessURL(url);	
}

function DoSearch()
{
	url = '#products.php?search='+$('input#searchtext').val();
	document.location = url;
	// return false to prevent default action on form.
	return false;
}

function ProcessURL(url)
{
	var params = $.deparam.fragment( url, true );
	var an_cath = "";
	var an_op = "";
	//$("#test").append("proc: " + params.toString() + ": "+url +"<br/>");
	
	// remove styles from current selection
	if( last != null)
	{
		last.removeClass('ui-state-active');
	} else {
		$('div[class=lev-2]').removeClass('ui-state-active');
	}
	
	// debug info add: &debug=1 after adress
	if(params['debug'])
	{
		$('.ui-layout-north').append( JSON.stringify( params, null, 2 ) );
		$('.ui-layout-north').append('<br/>'+url);
	}
	
	
	if(params['cath'])
	{
		var cath = params['cath'];
		an_cath = cath;
		showMenu(cath);
		if(cath=='home')
		{
			url = "home.php";
			$('#accordion-title').text("Home");
			an_op = "home";
		} else if(params['products.php?pid']){
			//url = 'products.php?pid='+params['products.php?pid'];
		} else {
			url = "cathegories/"+cath+".html";
			an_op = "cath-home";
		}
	}
	else{
		// Show and higlight path for current item in menu
		if(params['p1'])
		{
			var p1 = params['p1'];
			var anch = $('a#'+p1);
			var cath = anch.parents('div[class=lev-2]').attr('cath');
			showMenu(cath);
			
			anch.parents('div[class|=lev]').show();
			anch.addClass('ui-state-active');
			last = anch;
			an_cath = cath;
			an_op = anch.text();
		} else {
			var anch = $('a[cath='+params['products.php?cath']+']');
			var cath = anch.parents('div[class=lev-2]').attr('cath');
			showMenu(cath);
			
			anch.parents('div[class|=lev]').show();
			anch.addClass('ui-state-active');
			last = anch;
			an_cath = cath;
			an_op = anch.text();
		}
	}
	/*
	if(params['p'])
	{
		var p = params['p'];
		var anch = $('a#'+p[0]);
		//anch.click();
		var cath = anch.attr('cath');
		if(!cath)
		{
			//cath = 'home';
		}
		showMenu(cath);
		//anch = anch.parent();
		anch = $('div[cath='+cath+']');
		for( i=1 ; i < p.length ; i++)
		{
			//anch = anch.next('div').children('#'+p[i]);
			anch = anch.children('#'+p[i]);
			anch.next('div').show('fast');
			//anch.append('#');
			if(i == p.length-1)
			{
				anch.addClass('ui-state-active');
				last = anch;
			}
			anch = anch.next('div');
		}
	} else {
		//viewMenu('home');
	}
	*/
	/*
	if(master){
		var u = url.replace(/\&/g,'|');
		$.get('http://lan1/ny/remote.php?d=34&path='+u);
		//$('.result').append(u).append('<br/>');
	}
	*/
	_gaq.push(['_trackEvent', an_cath, an_op, url]);
	//$("#test").append("url: " + url + "<br/>");
	goh(url);
}
 
// get the data from href and present it in #subframe
// Sets up lightbox and document title
// initiates a scroll to the selected news
function goh(href){
	if(href=='')
	{
		viewMenu('home');
		return;
	}
	$.ajax({
		url: href,
		cache : false,
		success: function(data) {	
			// Set contents
			$('#subframe').html(data);
	
			// init lightbox for all images
			$('.lightbox a').lightBox({maxImageWidth: 600, minImageWidth: 300, overlayOpacity: 0.1});
		    $('.ui-icon').hover(
	
		            function(){ $(this).addClass('icon-active'); }, 
	
		            function(){ $(this).removeClass('icon-active'); }
	
		     );
	
			// setup document title from div#page-title
			var titlediv = $('div#page-title');
			var tit = 'Acoutronic AB';
			if(titlediv.text() != '')
			{
				tit = tit + ', '+titlediv.text() + ' ' + titlediv.next('.prod-head').text();
			} else {
				if(last != null)
				{
					tit = tit + ', ' + last.text();
				}
			}
			document.title = tit;
	
			// initiate scroll if #SCR is present
			window.setTimeout(function(){
				var ScrollTarget = $('#SCR');
				if (ScrollTarget.length != 0)
				{
					//$('#subframe').scrollTo(ScrollTarget,300);
					$(document).scrollTo(ScrollTarget,300);
				}
			},20);
				
			/*
			var newspos = $('#SCR');
			var p = newspos.position();
			if(p != null)
			{
				var h = p.top - ($('#subframe').position().top - $('#subframe').scrollTop());
				$('#subframe').scrollTop(h);
			}
			*/
		},
		error: function(XMLHttpRequest, textStatus, errorThrown)
		{
			$('#subframe').html("Error retreiving page.");
		}
	});
}


// handles Reminder List
var interest_arr = new Array();

function addToCart(pid,h)
{
	$('#interest-list-widget').show();
	interest_arr.push(pid);
	href = '#'+$.param.fragment();
	$("#interestlist").append($('<div>').html($('<a>').attr('href',href).text(pid).css('font-weight','bold')).append($('<div>').text(h).css('font-size','0.8em'))).effect("highlight", {}, 500);
	try {
		if($.jStorage.storageAvailable())
		{
			//localStorage["ITLIST"] = Base64.encode($("#interestlist").html());
				$.jStorage.set("interest.list", Base64.encode($("#interestlist").html()));			
		}
	} catch (e) {
	}
	$('div#il-mail').show();
	$('div#il-trash').show();
	_gaq.push(['_trackEvent', "reminder", "add", h]);
}
