var userAgent = navigator.userAgent.toLowerCase();
var musicPlaying = false;
 
jQuery.browser = {
	version: (userAgent.match( /.+(?:rv|it|ra|ie|me)[\/: ]([\d.]+)/ ) || [])[1],
	chrome: /chrome/.test( userAgent ),
	safari: /webkit/.test( userAgent ) && !/chrome/.test( userAgent ),
	opera: /opera/.test( userAgent ),
	msie: /msie/.test( userAgent ) && !/opera/.test( userAgent ),
	mozilla: /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent )
};

var activeShortURL = "";
var searchTimer = 0;
var activeSection = "";

$(document).ready( function () {
	installHandlers();		
	if (!$.browser.chrome && !$.browser.safari)
		$.historyInit(checkActiveContent);		
});

function showHomePage() {

	$("#header").fadeOut("slow");
	$("#content").fadeOut("slow");
	$("#container").css("display", "none"); 
	document.title = "Retete - Carte de bucate | Mujdei.ro";
}

function loadActiveContent(url) {	
	$.getJSON(url, "", function(data) {
		$("#sectionCaption").html(data.SECTION_CAPTION);
		$("#title").text(data.TITLE);			
		$("#subTitle").text(data.SUBTITLE);						
		$("#upperTitle").text(data.UPPERTITLE);	
		$("#content").html(data.CONTENT);

		if (data.EXTRA_MENU != undefined)
		{					
			if ($("#extraMenu").html() == "")
				$("#extraMenu").html(data.EXTRA_MENU);				
		}
		else
		{
			$("#extraMenu").html("");	
		}					
								
		$("#menu").html("");
		if (data.MENU != undefined)
		{
			$.each(data.MENU, function(i, item) {
				$("#menu").append('<div><a href="'  + item.URL + '#' + item.SHORT_URL + '" activeURL="' + item.ACTIVE_URL+ '">' + item.CAPTION + '</a></div>');	
			});			
		}
		document.title = data.TITLE + " " + data.SECTION_CAPTION + " | Mujdei.ro";
		var head = document.getElementsByTagName('head')[0];
		$(document.createElement('link'))		
		.attr({type: 'text/css', href: "/" + data.SECTION + ".css", rel: 'stylesheet', media: 'screen'})
		.appendTo(head);
		
		//if (data.SECTION != activeSection) {
			$("#articleBanner").html("<iframe src='/" + data.SECTION + ".ad?ad=2' scrolling='no' width='100%' height='100%'></iframe>"); 
			$("#banner1").html("<iframe src='/" + data.SECTION + ".ad?ad=4' scrolling='no' width='100%' height='100%'></iframe>");
			$("#banner2").html("<iframe src='/" + data.SECTION + ".ad?ad=1' scrolling='no' width='100%' height='100%'></iframe>");
			$("#banner3").html("<iframe src='/" + data.SECTION + ".ad?ad=3' scrolling='no' width='100%' height='100%'></iframe>");
			activeSection = data.SECTION;
		//}
		$("#container").show();		
		
		try {
		var pageTracker = _gat._getTracker("UA-9567432-1");
		pageTracker._trackPageview();
		} catch(err) {}
		installHandlers();	
	});
	
	$("#header").fadeIn("slow");
	$("#content").fadeIn("slow");					
}


function introMovie_DoFSCommand(command, args) {
	activeShortURL = args;						
	window.location.hash = activeShortURL;	
	if (command == "loadSection")
	{
		loadActiveContent("/" + args + "/list.json");
	}
	else if (command == "loadPage")
	{	
		loadActiveContent("/" + args + ".json");
	}
	/*else if (command == "switch-music")
	{
		if (musicPlaying == false)
		{
			soundManager.play('sound1');
		}
		else
		{
			soundManager.stop("sound1");
		}
		musicPlaying = !musicPlaying;
	}*/
}

function loadSearchResults(searchTerms, exactSearch) {
	$("#content").html("<table width='100%' height='100%'><tr><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td></tr><tr height='*' valign='middle'><td>&nbsp;</td><td align='center'><img src='/images/loader.gif'></td><td>&nbsp;</td></tr><tr><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td></tr></table>");
	$.getJSON("/search.json?terms=" + searchTerms + "&exact=" + exactSearch , "", function(data) {		
		$("#content").html(data.CONTENT);
		$("#banner1").html("<iframe src='/" + data.SECTION + ".ad?ad=4' scrolling='no' width='100%' height='100%'></iframe>"); 
		$("#banner2").html("<iframe src='/" + data.SECTION + ".ad?ad=1' scrolling='no' width='100%' height='100%'></iframe>"); 
		$("#banner3").html("<iframe src='/" + data.SECTION + ".ad?ad=3' scrolling='no' width='100%' height='100%'></iframe>");
		if (exactSearch)
		{
			window.location.hash = "search_ex_"+ searchTerms;	
		}		
		else
		{
			window.location.hash = "search_"+ searchTerms;
		}
		installHandlers();	
	});						
}

function installHandlers() {
	$("a").live("click",  function() {
		if (this.attributes["activeURL"]) {
			var shortURL =  this.hash.substr(1, this.hash.length - 1);	
			if (shortURL!= "") {
				activeShortURL = shortURL;						
				window.location.hash = shortURL;				
			}					
			loadActiveContent(this.attributes["activeURL"].value);			
			return false;			
		}
	});
	
	
	$(".homeLink").click(function () {
		showHomePage();
		window.location.hash = "home";
		return false;
	});
	
	$("#txtSearch").keyup(function () {
		doSearch();			
	})
	$("#chkExactSearch").change(function () {
		doSearch();			
	})
	
	if (activeShortURL.indexOf("search_") == 0)
	{
		$("#txtSearch").focus();
	}
	
	$(".scroll-pane").jScrollPane();
}


function doSearch() {
	if (searchTimer != 0) {
		clearTimeout(searchTimer);			
	}
	var searchTerms = $("#txtSearch").val();
	
	if (searchTerms.length >= 3)
		searchTimer = setTimeout("loadSearchResults('" + searchTerms.replace(/ /g, "+") + "'," + ($("#chkExactSearch").attr("checked")) + ")", 300);
}
function checkActiveContent(shortURL) {	
	if (shortURL != activeShortURL) {
		if (shortURL == "home") {
			activeShortURL = shortURL;
			showHomePage();
			
		}
		else {
			activeShortURL = shortURL;			
			loadActiveContent("/proxy?url=" + shortURL);
		}
	}	

}



function validateSubmitForm(f) {
	$.validator.addMethod("newIngred", function(value) {
		if( (value.substring(0, 25) == "Ingredient 1 si cantitate") || (value == ""))
			return false;
		else
			return true;
	}, 'Nu ai completat ingredientele!');

	$.validator.addMethod("newContent", function(value) {
		if( value == "" || value == "Aici introduci Modul de Preparare")
			return false;
		else
			return true;
	}, 'Nu ai completat modul de preparare!');
		
	$("#frmSubmitForm").validate({
		invalidHandler: function() {
    		$("#poze").hide();
  		},
		rules: {
			name: "required",
			mail:{
				required: true,
				email: true				
			},			
			title: "required",
			ingrediente: "newIngred",
			content: "newContent",
			terms: "required"
		},
		messages: {
			name: 'Nu ai completat numele!',
			mail: {
				required: 'Nu ai completat adresa de e-mail!',
				email: 'Adresa de e-mail nu este valida!'			
			},
			title: 'Nu ai completat denumirea retetei!',
			terms:{
				required: 'Trebuie sa accepti regulamentul pentru a putea adauga retete!'
			}
		},
		success: function() {
			if($("#frmSubmitForm").validate().numberOfInvalids() == 0)
			{
				$("#poze").show();
				return false;
			}
		}
	});
	return $("#frmSubmitForm").valid();
}

function validateSubmitCommentForm(f) {
	$("#frmCommentForm").validate({
		rules: {
			name: "required",
			mail:{
				required: true,
				email: true				
			},			
			text: "required",
			terms: "required"
		},
		messages: {
			name: 'Nu ai completat numele!',
			mail: {
				required: 'Nu ai completat adresa de e-mail!',
				email: 'Adresa de e-mail nu este valida!'				
			},
			text: 'Nu ai completat cometariul!',
			terms:{
				required: 'Trebuie sa accepti regulamentul pentru a putea adauga comentarii!'
			}
		}
	});
	return $("#frmCommentForm").valid();
}

function doSubmitCommentForm(f) {
	if (validateSubmitCommentForm(f)) {		
		var data = new Array();
		data[data.length] = {
			name: "name",
			value: f.name.value
		};
		data[data.length] = {
			name: "mail",
			value: f.mail.value
		};
		data[data.length] = {
			name: "text",
			value: f.text.value
		};
		data[data.length] = {
			name: "terms",
			value: f.terms.value
		};
		
		$.post(f.action + ".json", data, function(result) {
			$("#content").html(result.CONTENT);
		}, "json");	
	}
	
	return false;
}
function doSubmitForm(f) {
	$("#poze").hide();
	if (validateSubmitForm(f)) {
		var data = new Array();
		data[data.length] = {
			name: "name",
			value: f.name.value
		};
		data[data.length] = {
			name: "title",
			value: f.title.value
		};
		data[data.length] = {
			name: "mail",
			value: f.mail.value
		};
		data[data.length] = {
			name: "ingrediente",
			value: f.ingrediente.value
		};
		data[data.length] = {
			name: "content",
			value: f.content.value
		};
		data[data.length] = {
			name: "terms",
			value: f.terms.value
		};
		
		$.post(f.action + ".json", data, function(result) {
			$("#content").html(result.CONTENT);
		}, "json");	
	}
	
	return false;
}
function validateContactForm(f){
	$("#frmContactForm").validate({
		rules: {
			name: "required",
			mail:{
				required: true,
				email: true				
			},			
			text: "required",
			terms: "required"
		},
		messages: {
			name: 'Nu ai completat numele!',
			mail: {
				required: 'Nu ai completat adresa de e-mail!',
				email: 'Adresa de e-mail nu este valida!'			
			},
			text: 'Nu ai completat mesajul!',
			terms:{
				required: 'Trebuie sa accepti termenii si conditiile pentru a trimite un mesaj!'
			}
		}
	});
	return $("#frmContactForm").valid();
}

function doSubmitContactForm(f){
	if(validateContactForm(f)){
		var data = new Array();
		data[data.length] = {
			name: "name",
			value: f.name.value
		};
		data[data.length] = {
			name: "mail",
			value: f.mail.value
		};
		data[data.length] = {
			name: "text",
			value: f.text.value
		};
		data[data.length] = {
			name: "terms",
			value: f.terms.value
		};
		
		$.post(f.action + ".json", data, function(result) {
			$("#content").html(result.CONTENT);
		}, "json");		
	}
	return false;
}