/* jQuery Session vars v.0.3
 * by Jay Salvat
 * http://www.jaysalvat.com
 * -----------------------------------------------
 * Inspired by an idea from Mario Heiderich
 * http://code.google.com/p/quipt/
 * -----------------------------------------------
 * Requires jquery.json.js by DeadWisdom
 * http://code.google.com/p/jquery-json/
 * -----------------------------------------------
 * CHANGELOG
 * 0.3 -- 11-JUL-08
 * Security improvements
 * Calling manually sessionStart and sessionStop is not required anymore
 * Window.name is keept between pages
 * 0.2 -- 10-JUL-08
 * Now works with functions, objects and arrays
 * 0.1 -- 08-JUL-08
 * First draft
 * -----------------------------------------------
 * USAGE
 * - To Store
 * $(function() {
 * 	$.session("myVar, "value");
 * });
 *
 * - To Read
 * $(function() {
 * 	alert( $.session("myVar) );
 * });
*/
(function(a){function i(){stored=window.name.split("#"+e+"#");f=window.name=stored[0];if(data=stored[1])a.each(data.split(";"),function(c,b){parts=b.split("=");varName=parts[0];varValue=unescape(parts[1]);d[varName]=varValue})}function j(){var c=f+"#"+e+"#";a.each(d,function(b,g){if(b&&g)c+=b+"="+escape(g)+";"});window.name=c}var d={},f="",e=location.href.match(/\w+:\/\/[^\/]+/)[0],h=document.referrer?document.referrer.match(/\w+:\/\/[^\/]+/)[0]:"";if(h==""||h!==e)window.name=window.name.replace("#"+ e+"#","");a.session=function(c,b){if(b){if(a.isFunction(b))b=b();d[c]=a.toJSON?a.toJSON(b):b}else return a.evalJSON?a.evalJSON(d[c]):d[c]};a.sessionStop=function(){j()};a.sessionStart=function(){i()};a.sessionStart();window.onunload=function(){a.sessionStop()}})(jQuery);

/*
 * jQuery JSON Plugin
 * version: 1.0 (2008-04-17)
 *
 * This document is licensed as free software under the terms of the
 * MIT License: http://www.opensource.org/licenses/mit-license.php
 *
 * Brantley Harris technically wrote this plugin, but it is based somewhat
 * on the JSON.org website's http://www.json.org/json2.js, which proclaims:
 * "NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.", a sentiment that
 * I uphold.  I really just cleaned it up.
 *
 * It is also based heavily on MochiKit's serializeJSON, which is
 * copywrited 2005 by Bob Ippolito.
 */

(function(d){function f(a){return a<10?"0"+a:a}Date.prototype.toJSON=function(a){return a.getUTCFullYear()+"-"+f(a.getUTCMonth()+1)+"-"+f(a.getUTCDate())};var g=/["\\\x00-\x1f\x7f-\x9f]/g,h={"\u0008":"\\b","\t":"\\t","\n":"\\n","\u000c":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"};d.quoteString=function(a){if(g.test(a))return'"'+a.replace(g,function(b){var c=h[b];if(typeof c==="string")return c;c=b.charCodeAt();return"\\u00"+Math.floor(c/16).toString(16)+(c%16).toString(16)})+'"';return'"'+a+'"'};d.toJSON= function(a){var b=typeof a;if(b=="undefined")return"undefined";else if(b=="number"||b=="boolean")return a+"";else if(a===null)return"null";if(b=="string")return d.quoteString(a);if(b=="object"&&typeof a.toJSON=="function")return a.toJSON();if(b!="function"&&typeof a.length=="number"){for(var c=[],e=0;e<a.length;e++)c.push(d.toJSON(a[e]));return"["+c.join(", ")+"]"}if(b=="function")throw new TypeError("Unable to convert object of type 'function' to json.");c=[];for(e in a){b=typeof e;if(b=="number")b= '"'+e+'"';else if(b=="string")b=d.quoteString(e);else continue;val=d.toJSON(a[e]);typeof val=="string"&&c.push(b+": "+val)}return"{"+c.join(", ")+"}"};d.evalJSON=function(a){return eval("("+a+")")};d.secureEvalJSON=function(a){var b=a;b=b.replace(/\\["\\\/bfnrtu]/g,"@");b=b.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]");b=b.replace(/(?:^|:|,)(?:\s*\[)+/g,"");if(/^[\],:{}\s]*$/.test(b))return eval("("+a+")");else throw new SyntaxError("Error parsing JSON, source is not valid."); }})(jQuery);


//fontsize
$(document).ready(function(){

	var originalFontSize = $('html').css('font-size');

	// Reset Font Size
	if ($.session("fontSize")){
		$('body').css('font-size', $.session("fontSize") + 'px');
	};
  /*
  * Sessions
  */
	$('#increaseFont').click(function(){
		if ($('body').css('font-size') == '8px') {
			$('body').css('font-size', '9px'); //11px
			$.session("fontSize", 9);
		} else if ($('body').css('font-size') == '9px') {
			$('body').css('font-size', '10px'); //11px
			$.session("fontSize", 10);
		} else if ($('body').css('font-size') == '10px') {
			$('body').css('font-size', '11px'); //11px
			$.session("fontSize", 11);
		} else if ($('body').css('font-size') == '11px') {
			$('body').css('font-size', '12px'); //12px
			$.session("fontSize", 12);
		} else {
			$('body').css('font-size', '10px'); //12px
			$.session("fontSize", 10);
		}
		return false;
	});

	$('#decreaseFont').click(function(){
		if ($('body').css('font-size') == '12px') {
			$('body').css('font-size', '11px'); //11px
			$.session("fontSize", 11);
		} else if ($('body').css('font-size') == '11px') {
			$('body').css('font-size', '10px'); //12px
			$.session("fontSize", 10);
		} else if ($('body').css('font-size') == '10px') {
			$('body').css('font-size', '9px'); //12px
			$.session("fontSize", 9);
		} else if ($('body').css('font-size') == '9px') {
			$('body').css('font-size', '8px'); //12px
			$.session("fontSize", 8);
		} else {
			$('body').css('font-size', '10px'); //12px
			$.session("fontSize", 10);
		}
		return false;
	});


	if(window.sidebar) { // Mozilla Firefox Bookmark
		$('#firefox_bookmark').show();
	} else if (window.external) { // IE Favorite
		$('#ie_bookmark').show();
	} else {
		$('#other_bookmark').show();
	}

	$('div#s2f div.bg').css({ opacity: 0.8 });
	$('div.tools a.mail').bind('click', openS2F);
	$('div#s2f a.close').bind('click', closeS2F);


	$.datepicker.setDefaults( $.datepicker.regional[ "et" ] );

	$(".datepicker" ).datepicker({
		showOn: "both",
		buttonImage: "/extensions/esf/images/ico-calendar.gif",
		buttonImageOnly: true,
		buttonText: 'Vali kuupäev',
		changeMonth: true,
		changeYear: true
	});

	$(".question").tinyTips("light", "title");
	$('#s').css('background-image', 'url(img/bg-g-customsearch.gif)');

	$('#s').focus(function() {
		$(this).css('background-image', 'none');
	});
	/*
	$('div#s2f div.bg').css({ opacity: 0.8 });
	$('div.tools a.mail').bind('click', openS2F);
	$('div#s2f a.close').bind('click', closeS2F);
	*/
});

function email_check(str) {

	var at="@";
	var dot=".";
	var lat=str.indexOf(at);
	var lstr=str.length;
	var ldot=str.indexOf(dot);

	if (str.indexOf(at)==-1) {
		return false;
	}
	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr) {
		return false;
	}
	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr) {
		return false;
	}
	if (str.indexOf(at,(lat+1))!=-1) {
		return false;
	}
	if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot) {
		return false;
	}
	if (str.indexOf(dot,(lat+2))==-1) {
		return false;
	}
	if (str.indexOf(" ")!=-1) {
		return false;
	}
	return true;
}

function joinNewsLetter() {
	$('.newsletter_box').show();
}

function newsLetterSubmit() {

	data = new Object;
	data.name = $('#newsletter_name').val();
	data.mail = $('#newsletter_mail').val();

	$.post("/newsletter.php", data,
	function(result){
		$('.newsletter_box').find('.button').hide();
		$('#newsletter_text').hide();
		$('#close_button').css('display', 'inline-block');
		$('.newsletterField').hide();
		$('#newsletter_message_' + result).show();
	});

}

function openS2F()
{
	$('div#s2f').show();
	$('div#s2f').bind('click', function(e) {
		var clicked = $(e.target);
		if (!(clicked.is('div#s2f div.content') || clicked.parents().is('div#s2f div.content'))) {
			closeS2F();
		}
	});
	return false;
}
function closeS2F()
{
	$('div#s2f').hide();
	$('div#s2f').unbind();
	return false;
}

function send2friend(url)
{
	data = new Object();

	error = false;

	data.sender_name = $('#s2f_y_name').val();
	data.sender_mail = $('#s2f_y_email').val();
	data.reciver_name = $('#s2f_f_name').val();
	data.reciver_mail = $('#s2f_f_email').val();
	data.url = url;

	$('.s2f-form').find('label').css('color', 'black');
	$('.s2f_error_message').hide();

	if(!email_check($('#s2f_y_email').val())) {
		$('#sender_mail').css('color', 'red');
		$('#sender_mail_error').show();
		error = true;
	}
	if(!email_check($('#s2f_f_email').val())) {
		$('#reciver_mail').css('color', 'red');
		$('#receiver_mail_error').show();
		error = true;
	}
	if($('#s2f_y_name').val() == '') {
		$('#sender_name').css('color', 'red');
		$('#sender_name_error').show();
		error = true;
	}
	if($('#s2f_f_name').val() == '') {
		$('#reciver_name').css('color', 'red');
		$('#receiver_name_error').show();
		error = true;
	}

	if(error)
		return false;

	$.post("/s2f.php", data,
	function(answer){
		/*console.log(result);*/

		if(answer == 'ok') {
			$('#s2f_success').show();
			$('#s2f_form').hide();
		} else {
			$(result).each(function(i, item) {
				$('#' + item).css('color', 'red');
			});
		}
	}, "html");

}
/* Map stuff start */
function areaOver()
{
	var index = $(this).attr("class").split("-")[1];
	var pos = 450 * index;
	$(".map-hover").css({ "background-position": "0 -" + pos + "px" });
}

function areaOut()
{
	$(".map-hover").css({ "background-position": "0 0" });

}

var send = true;

function getToolTipContent(data, name) {
	if (xhr) {
		xhr.abort();
	}

	if (send == true) {
		var xhr = $.ajax({
			type: "POST",
			data: data,
			dataType: "json",
			url: '/saajad_maakonniti.php',
			success: function(data) {
				$('#tip_content').find('h3').html(name);
				$('#tip_content').find('#total_sum').html(data.total_sum);
				$('#tip_content').find('#total_companies').html(data.total_companies);
				$('#tip_content').find('#total_projects').html(data.total_projects);
				$('#tip_content').find('#most_popular').html(data.most_popular);
				$('#tip_content').find('.deactive').show();
				$('#tip_content').find('.active').hide();
				send = true;
			}
		});
	} else {
		if (xhr) {
			xhr.abort();
			$('#tip_content').html('<div class="tip-content active">Laen...</div>');
		}
	}

	send = false;

}

$(function()
{
	if($("area").length > 0) {
		$("area").hover(areaOver, areaOut);
		$("area").click(function(){
			return false;
		});
		$("area").tooltip({
			bodyHandler: function() {
				$('#tip_content').find('.deactive').show();
				$('#tip_content').find('.active').hide();
				data = {};
				data.county = $(this).attr("href");
				name = $(this).attr('name');
				setTimeout("getToolTipContent(data, name)",1000);

				return '<div id="tip_content"><div class="tip-content active">Laen...</div>' + $('#tip-content').html() + '</div>';
			},
			showURL: false,
			track: true
		});
	}

  if ($(".meetmevorm").length > 0)
  {
    validateF1();
  }

  $(".disabled").live("click", function(){return false;});

  $(".meetmevorm select").change(function(){validateF1();});
  $(".meetmevorm input").keyup(function(){validateF1();});
});

/* Map stuff end */

/* functions, do not edit */

/***********************************************************/
/*                    tinyTips Plugin                      */
/*                      Version: 1.1                       */
/*                      Mike Merritt                       */
/*                 Updated: Mar 2nd, 2010                  */
/***********************************************************/

(function($){
	$.fn.tinyTips = function (tipColor, supCont) {

		if (tipColor === 'null') {
			tipColor = 'light';
		}

		var tipName = tipColor + 'Tip';

		/* User settings
		**********************************/

		// Enter the markup for your tooltips here. The wrapping div must have a class of tinyTip and
		// it must have a div with the class "content" somewhere inside of it.
		var tipFrame = '<div class="tooltip ' + tipName + '"><div class="header"></div><div class="content"></div><div class="footer"></div></div>';

		// Speed of the animations in milliseconds - 1000 = 1 second.
		var animSpeed = 0;

		/***************************************************************************************************/
		/* End of user settings - Do not edit below this line unless you are trying to edit functionality. */
		/***************************************************************************************************/

		// Global tinyTip variables;
		var tinyTip;
		var tText;

		// When we hover over the element that we want the tooltip applied to
		$(this).hover(function() {

			// Inject the markup for the tooltip into the page and
			// set the tooltip global to the current markup and then hide it.
			$('body').append(tipFrame);
			var divTip = 'div.'+tipName;
			tinyTip = $(divTip);
			tinyTip.hide();

			// Grab the content for the tooltip from the title attribute (or the supplied content) and
			// inject it into the markup for the current tooltip. NOTE: title attribute is used unless
			// other content is supplied instead.
			if (supCont === 'title') {
				var tipCont = $(this).attr('title');
			} else {
				var div = $(this);

				var title = div.children(".title").html();
				var author = div.children(".author").html();
				var price = div.children(".price").html();
				var tipCont = '<h3>' + title +' </h3><p>' + author +' </p><p>' + price +' </p>' ;
			}
			$(divTip + ' .content').html(tipCont);
			tText = $(this).attr('title');
			$(this).attr('title', '');

			// Offsets so that the tooltip is centered over the element it is being applied to but
			// raise it up above the element so it isn't covering it.
			var yOffset = tinyTip.height() + 2;
			var xOffset = 0;

			// Grab the coordinates for the element with the tooltip and make a new copy
			// so that we can keep the original un-touched.
			var pos = $(this).offset();
			var nPos = pos;

			// Add the offsets to the tooltip position
			nPos.top = pos.top - yOffset;
			nPos.left = pos.left - xOffset;

			// Make sure that the tooltip has absolute positioning and a high z-index,
			// then place it at the correct spot and fade it in.
			tinyTip.css('position', 'absolute').css('z-index', '1000');
			tinyTip.css(nPos).fadeIn(animSpeed);

		}, function() {

			$(this).attr('title', tText);

			// Fade the tooltip out once the mouse moves away and then remove it from the DOM.
			tinyTip.fadeOut(animSpeed, function() {
				$(this).remove();
			});

		});

	}

})(jQuery);

function validateF1(){

  var ok = 0;

  $('.meetmevorm :input').each(function(){
    if ($(this).val() != "" && !$(this).is(":hidden") && !$(this).is(":submit")) ok = 1;
  });


  if (ok == 0){
    $('#meetmed_search').addClass("disabled");
    $('.meetmevorm .button').addClass("disabled");
  } else {
    $('#meetmed_search').removeClass("disabled");
    $('.meetmevorm .button').removeClass("disabled");
  }
}
