/**
 * Site functionalities
 * 
 * Copyright (c) 2009 Peter Cicman, Divio GmbH. 
 */

$(function(){
	$(document).ajaxSend(function(event, xhr, settings) {
		function getCookie(name) {
			var cookieValue = null;
			if (document.cookie && document.cookie != '') {
				var cookies = document.cookie.split(';');
				for (var i = 0; i < cookies.length; i++) {
					var cookie = jQuery.trim(cookies[i]);
					// Does this cookie string begin with the name we want?
					if (cookie.substring(0, name.length + 1) == (name + '=')) {
						cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
						break;
					}
				}
			}
			return cookieValue;
		}
		function sameOrigin(url) {
			// url could be relative or scheme relative or absolute
			var host = document.location.host; // host + port
			var protocol = document.location.protocol;
			var sr_origin = '//' + host;
			var origin = protocol + sr_origin;
			// Allow absolute or scheme relative URLs to same origin
			return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
				(url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
				// or any other URL that isn't scheme relative or absolute i.e relative.
				!(/^(\/\/|http:|https:).*/.test(url));
		}
		function safeMethod(method) {
			return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
		}

		if (!safeMethod(settings.type) && sameOrigin(settings.url)) {
			xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
		}
	});
	function dataSource(term, limit, callback){
		var collection = 'saison_recipe'

		$.R('search.views.autocomplete', [term, collection, limit], function(result){
			parsed = [];
			obj = result[0]
			for (var i=0; i < obj.length; i++){
				parsed[parsed.length] = {data: [obj[i][2], obj[i][1], obj[i][5], obj[i][0], null], value: obj[i][1].toString(), result: obj[i][1]};
				var results = obj[i][3];
				for (var j=0; j < results.length; j++){
					results[j][results[j].length] = obj[i][0];
					parsed[parsed.length] = {data: results[j], value: results[j][1].toString(), result: results[j][1]};
				}
				
			}
			
			if (obj.length > 0) {
				var showAll = result[1];
				parsed[parsed.length] = {data: showAll, value: showAll[1].toString(), result: showAll[1]};
			}
			
			callback(parsed);
		});
	}
	try{
		$("#search").autocomplete(dataSource, {
			formatItem: function(row) {
				//console.log(row);
				if (row.length == 5) {
					// title
					return '<div class="' + row[3] + '"><div class="heading"><h3>' + row[1] + '</h3> <span class="extra">(' +  row[2]+ ')</span></div></div>';
				} else if (row.length == 2) {
					// show all button
					return '<div class="item"><p class="show-all">' + row[1] + '</p></div>';
				}
				// entry
				return '<div class="' + row[3] + ' "><div class="item"><h4>' + row[1] + '</h4><p>' + row[2] + '</p></div></div>';
			},
			scroll: false,
			max: 20,
			minChars: 3,
			autofill: false,
			width: '26.99em',
			resultsClass: "searchresults-autocomplete ac_results"
		}).bind("result", function(el, data) {
			window.location.href = data[0];
			});
	} catch(err){}
	
	$('#searchbox select').change(function(){
		$("#search").flushCache();
	});

	$('#recipe-search-btn').click(function(e){
		var s = $('#search');
		if (s.hasClass('blur')){
			e.preventDefault();
			window.location = $('#recipe-page-lnk')[0].href;
		}
	});

	$('.cms_toolbar_submenubutton').bind('click', function(){
		var that = $(this);
		var container = that.parents('div.subcolumns');
		if (container.length){
			if (that.hasClass('open')){
				container.removeClass('toolbar');
			} else {
				container.addClass('toolbar');
			}
		}
	});

	
	// contrast switcher
	$('#contrast-switch').click(function(){
		saison.toggleContrast();
		return false;
	});

	$('.page_account-messages a').each(function(){
		var that = $(this);
		this.innerHTML = this.innerHTML.replace('()', '(' + $('#messages-count').html() + ')');
	});
});

var saison = {
	highContrast: $.cookie('high-contrast') || "",

	toggleContrast: function(contrast) {
		if (contrast == undefined) {
			contrast = saison.highContrast = saison.highContrast == 1 ? "" : 1;
		}
		
		$.cookie('high-contrast', contrast, { expires: 7, path: '/' });
		if (contrast) {
			$('head').append('<link href="/media/static/css/screen/contrast.css" rel="stylesheet" type="text/css" />');
		} else {
			$('link[href="/media/static/css/screen/contrast.css"]').each(function() { this.disabled=true });
			$('link[href="/media/static/css/screen/contrast.css"]').remove();
		}
	}
	
}

// switch contrast here if required
saison.toggleContrast(saison.highContrast);

/*
 * Image preview script 
 */
this.imagePreview = function(){	
	/* CONFIG */
		xOffset = 150;
		yOffset = 30;
		
		// these 2 variable determine popup's distance from the cursor
		// you might want to adjust to get the right result
		
	/* END CONFIG */
	$("a.preview").hover(function(e){
		this.t = this.title;
		this.title = "";
		var c = (this.t != "") ? "<br/>" + this.t : "";	
		if ( this.rel.substr(0,3) == "id:" ) {
			// the preview content is a id of a div containing the content
			var content_id = this.rel.substr(3,this.rel.length);
			var content = "<div id='preview'>" + $("#"+content_id).html()  + "</div>";
			$("body").append( content );
			//alert(content);
		} else if (( this.rel.substr(0,5) == "ajax:" )) {
			// do stuff for ajax fetching
		} else {
			$("body").append("<div id='preview'><img src='"+ this.rel +"' alt='Image preview' />"+ c +"</div>");
		};
										 
		$("#preview")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px")
			.fadeIn("fast");						
	},
	function(){
		this.title = this.t;	
		$("#preview").remove();
	});	
	$("a.preview").mousemove(function(e){
		$("#preview").css("top",(e.pageY - xOffset) + "px").css("left",(e.pageX + yOffset) + "px");
	});			
};

// starting the script on page load
$(document).ready(function(){
	imagePreview();
	$("a[href='/fr/recettes/None/detail/']").hide();
	$("a[href='/it/ricette/None/detail/']").hide();
	$("a[href='/de/rezepte/None/detail/']").hide();
});

