/*
 * In this file are effects / functions which are common for most pages
 */

$.browser.ie6 = ($.browser.msie && parseInt($.browser.version) <= 6);

String.prototype.trim = function () {
	return this.replace(/^[\s]+|[\s]+$/g, '');
};
String.prototype.trimMultiline = function () {
	return this.replace(/^[\s\r\n]+|[\s\r\n]+$/g, '');
};

/* 
 * Stops event propagation
 * Needed because jQuery return false also prevents default action, which
 * in some cases is not desired effect.
 */
function stopEventPropagation(e)
{
	if(!e) e = window.event;
	if (e.stopPropagation)
		e.stopPropagation();
	else
		e.cancelBubble = true;
}

function ieFixes()
{
	if ($.browser.msie)
	{
		/* Because of IE hasLayout, it's impossible to move element to the left by 1px.
		 * To get required visual appearance removing previous siblings right line */
		 	 
			$('div.submenu li.active').each(function () { $(this).prev().children('span').eq(0).css('background', 'transparent'); })

		/* IE 6 */
		if ($.browser.ie6) {
			/* IE6 Cursor fix */
				$('.force_cursor li').click(function () {
					document.location = $('a', this).attr('href');
				});
				
			/*
			 * Internet Explorer 6 PNG image fix
			 * @usage Add "png" class to the image
			 */
				$('img.png').each(function () {
					if (/\.png$/i.test(this.src))
					{
						var source_image = this.src;
						this.src = '/img/px.gif';
						this.runtimeStyle.filter = "progid:DXImageTransform.Microsoft." +
		                    "AlphaImageLoader(src='" + source_image + "',sizingMethod='image')";
					}
				});
		}
	}
}

/*
 * Simple popup
 * Used for header language selector 
 */
function simplePopup (popup_element, callee_element)
{
	this.popup = $(popup_element);
	this.init($(callee_element));
};
//Popup state, true - visible, false, hidden
simplePopup.prototype.state = false;
//Popup element
simplePopup.prototype.popup = null;
//Class sub constructor	
simplePopup.prototype.init = function (callee_element) {
	//Reference to self
	var self = this;
	
	//Handle popup open
	callee_element.click(function (e) {
		if (self.state === false)
		{
			self.state = true;
			self.popup.slideDown();
		}
		
		//Cancel default event and stop  bubbling
		return false;
	});
	
	//If popup is clicked, not the document, then cancel $(document).click execution
	this.popup.click(function (e) {
		stopEventPropagation(e);
	});
	
	//Close popup if user click somewhere on the document
	$(document).click(function () {
		if (self.state)
		{
			self.state = false;
			self.popup.slideUp();
		}
	});
};

/* 
 * Adds empty input behaviour: when input is focused, default value is replaced with '',
 * when focus is lost, inputs value is replaced with default value if current value is ''
 * and class 'default' is added
 */
function EmptyInput(element) {
	var self = this;
	this.input_element = $(element);
	if (!this.input_element[0]) return;
	
	this.default_value = this.input_element.attr('title');
	this.input_element[0].emptyinput = this;
	
	this.input_element.blur(function () {
		self.onblur();
	});
	this.input_element.focus(function () {
		self.onfocus();
	});
	
	this.onblur();
};
EmptyInput.prototype.input_element = null;		//Input element 
EmptyInput.prototype.default_value = '';		//Default vlaue
EmptyInput.prototype.onfocus = function () {
	var val = this.input_element.val();
	val = (new String(val)).trimMultiline();
	
	if (val == this.default_value)
	{
		//Work around for textareas in IE6, which causes an error
		if ($.browser.ie6 && this.input_element[0].tagName == 'TEXTAREA')
			this.input_element.html('');
		else
			this.input_element.val('');
	}
	
	this.input_element.removeClass('default');
};
EmptyInput.prototype.onblur = function () {
	var val = this.input_element.val();
	val = (new String(val)).trimMultiline();
	
	if (val == '') val = this.default_value;
	if (val == this.default_value) {
		this.input_element.addClass('default');
		if ($.browser.ie6 && this.input_element[0].tagName == 'TEXTAREA')
			this.input_element.html(this.default_value);
		else
			this.input_element.val(this.default_value);
	}else{
		this.input_element.removeClass('default');
	}
};


/* Send to friend popup and form handle */
var SendToFriend = {
	el: null,						//Popup element
	links: null,					//Links which calls popup to show/hide (which has attribute href="#send-to-friend"
	popup_state: false,				//Popup state, true - visible, false - hidden
	form_url: '',					//Url to which will be sent ajax request, beeing set in 'init' function
	validation_errors: {error: false, to: false, name: false, comment: false},	//Validation
	initialized: false,				//Class has been initialized
	
	/* Send a request */
	send: function () {
		var form_data = {};
		if (!SendToFriend.validate()) return false;
		$('input[type="text"], textarea,input[type="hidden"]', SendToFriend.el).each(function () {
			form_data[$(this).attr('name')] = $(this).val();
			form_data[$(this).attr('name')] = form_data[$(this).attr('name')].trimMultiline();
			
			if (this.emptyinput)
			{
				 if (form_data[$(this).attr('name')] == this.emptyinput.default_value)
				 {
				 	form_data[$(this).attr('name')] = '';
				 }
			}
		});
		$.post(SendToFriend.form_url, form_data, SendToFriend.send_callback);
	},
	/* Funtions which is called after a submit */
	send_callback: function (output, textStatus) {
        if (textStatus == 'success') {
            $('.sendtofriend-form', SendToFriend.el).slideUp();
            $('.sendtofriend-confirmation', SendToFriend.el).slideDown();
            window.setTimeout(function(){
                SendToFriend.hide();
				setTimeout(function () {
				
					//Reset form: show form, hide confirmation window
					$('.sendtofriend-form', SendToFriend.el).show();
					$('.sendtofriend-confirmation', SendToFriend.el).hide();
					
					//Restore default values
					$('input[type="text"], textarea', SendToFriend.el).each(function () {
						if (this.emptyinput.default_value)
						{
							$(this).val(this.emptyinput.default_value);
							$(this).addClass('default');
						}
						else
							$(this).val('');
					});
					
				}, 500);
				
            }, 2000);
        } else {
            //Failed to send data
        }
	},
	/* Show popup */
	show: function () {
		if (!SendToFriend.initialized)
		{
			//Reposition form if it's on the page with breadcrumbs
			if ($('div.page-heading').hasClass('with-breadcrumbs'))
			{
				SendToFriend.el.addClass('isOnBreadcrumbsPage');
			}
			if (!$('div.page-heading a[href="#send-to-friend"]').is(':last-child'))
			{
				SendToFriend.el.addClass('rightOffset');
			}
			SendToFriend.initialized = true;
		}
		
		SendToFriend.links.addClass('active');
		SendToFriend.el.slideDown();
		SendToFriend.popup_state = true;
	},
	/* Hide popup */
	hide: function () {
		var fields = ['to', 'name', 'comment'];
		for(var i=0; i<fields.length; i++)
		{
			var field = $('#' + fields[i]);
			SendToFriend.validation_errors[fields[i]] = false;
			field.parent().parent().removeClass('error');
		}
		
		SendToFriend.links.removeClass('active');
		SendToFriend.el.slideUp();
		SendToFriend.popup_state = false;
	},
	validate:function () {
		var fields = ['to', 'name', 'comment'];
		SendToFriend.validation_errors.error = false;
		for(var i=0; i<fields.length; i++)
		{
			var field = $('#' + fields[i]);
			var value = (new String(field.val())).trimMultiline();
			var value_default = (new String(field.attr('title'))).trimMultiline();

			if (value == '' || value == value_default || (fields[i] == 'to' && !Validate.email(value)))
			{
				SendToFriend.validation_errors.error = true;
				if (!SendToFriend.validation_errors[fields[i]])
				{
					SendToFriend.validation_errors[fields[i]] = true;
					field.parent().parent().addClass('error');
				}
			}else{
				SendToFriend.validation_errors[fields[i]] = false;
				field.parent().parent().removeClass('error');
			}
		}
		
		if (SendToFriend.validation_errors.error)
		{
			$('div.sendtofriend p.error-message').slideDown();
		}else{
			$('div.sendtofriend p.error-message').slideUp();
		}
		
		return !SendToFriend.validation_errors.error;
	},
	/* Initialize popup and form */
	init: function () {
		SendToFriend.el = $('div.sendtofriend');
		
		/* Only continue if element exists */
		if (SendToFriend.el.length)
		{
			$('.sendtofriend-confirmation', SendToFriend.el).hide();

			SendToFriend.links = $('a[href="#send-to-friend"]');
			
			SendToFriend.form_url = (new String(document.location)).replace(document.location.hash, '');
			SendToFriend.links.click(function () {
				SendToFriend.popup_state = !SendToFriend.popup_state;
				if (SendToFriend.popup_state)
				{
					SendToFriend.show();
				}
				else
				{
					SendToFriend.hide();
				}
				return false;
			});
			
			SendToFriend.el.click(function () { return false; });
			
			$(document).click(function () {
				if (SendToFriend.popup_state)
				{
					SendToFriend.hide();
				}
			});
			
			SendToFriend.form_url = $('form', SendToFriend.el).attr('action');
			
			$('form', SendToFriend.el).submit(function () { SendToFriend.send(); });
			$('div.btn', SendToFriend.el).eq(0).click(function () { SendToFriend.send(); });
			
			$('input[type="text"], textarea').each(function () {
				new EmptyInput($(this));
			});
		}
	}
};


/* Breadcrumb navigation dropdown effect */
var Breadcrumbs = {
	data: {},							//link data
	sitemap_state: false,				//false - closed, true - open
	element_overlay: null,				//"breadcrumbs-overlay" element
	element_sitemap: null,				//"breadcrumbs-sitemap" element
	element_sitemap_cols: [],			//"breadcrumbs-sitemap" td elements
	hovered_group: '',					//Hovered elements group
	allow_close: true,
	
	/* Breadcrumb link was hovered, show overlay */
	hover: function (link) {
		link = $(link);
		var offset_x = link.offset().left - link.parent().offset().left - 9;
		var offset_y = parseInt(Breadcrumbs.element_overlay.css('marginTop'));
		
		if ($.browser.safari) offset_y = -17;
		
		$('a', Breadcrumbs.element_overlay).html(link.html()).attr('href', link.attr('href'));
		Breadcrumbs.element_overlay.css({
			marginLeft: offset_x + 'px',
			marginTop: offset_y + 'px',
			display: 'block'
		});
	},
	/* Fill sitemap with links */
	fill: function (group_name) {
		$('div', Breadcrumbs.element_sitemap).unbind('mouseenter').unbind('mouseleave');
		
		for(var i=0; i<3; i++)
		{
			$(Breadcrumbs.element_sitemap_cols[i]).html('');
		}
		
		if (!Breadcrumbs.data[group_name]) return;
		
		var item_count = 0;
		for(var i in Breadcrumbs.data[group_name]) item_count++;
		
		var items_per_col = Math.ceil(item_count / 3);
		var index = 0;
		
		for(var i in Breadcrumbs.data[group_name])
		{
			var col = Math.floor(index / items_per_col);
			if (Breadcrumbs.element_sitemap_cols[col])
			{
				$(Breadcrumbs.element_sitemap_cols[col]).append($('<div><span><a href="' + i + '">' + Breadcrumbs.data[group_name][i] + '</a></span></div>'));
			}
			
			index++;
		}
		
		$('div', Breadcrumbs.element_sitemap).hover(
							function () { $(this).addClass('hover'); },
							function () { $(this).removeClass('hover'); }
						);
		
		Breadcrumbs.element_sitemap.slideDown('fast');
	},
	/* Show sitemap */
	show: function () {
		Breadcrumbs.sitemap_state = true;
		Breadcrumbs.fill(Breadcrumbs.hovered_group);
		Breadcrumbs.element_overlay.addClass('open');
	},
	/* Hide sitemap */
	hide: function () {
		Breadcrumbs.element_sitemap.slideUp('fast', function () {
		Breadcrumbs.element_overlay.removeClass('open');
		Breadcrumbs.sitemap_state = false;
		if (Breadcrumbs.hovered_group == '')
			Breadcrumbs.element_overlay.css('display', 'none');
		});
	},
	/* Initialize */
	init: function () {
		if (!$('#breadcrumbs-list').length) return;
		
		$('div.page-heading').addClass('with-breadcrumbs');
		
		Breadcrumbs.element_overlay = $('#breadrumbs-overlay');
		Breadcrumbs.element_sitemap = $('#breadcrumbs-sitemap');
		Breadcrumbs.element_sitemap_cols = $('td', Breadcrumbs.element_sitemap);
		
		$('#breadcrumbs-list a[rel]').each(function () {
			var rel = $(this).attr('rel');
			if (Breadcrumbs.data[rel])
			{
				$(this).hover(function () {
					if (!Breadcrumbs.sitemap_state)
					{
						Breadcrumbs.hovered_group = rel;
						Breadcrumbs.hover(this);
					}
				}, function () {});
			}
		});

		Breadcrumbs.element_overlay.hover(function () {}, function () {
			if (!Breadcrumbs.sitemap_state)
			{
				Breadcrumbs.element_overlay.css('display', 'none');
			} else {
				Breadcrumbs.hovered_group = '';
			}
		});
		
		$('span', Breadcrumbs.element_overlay).click(function () {
			if (!Breadcrumbs.sitemap_state) {
				Breadcrumbs.show();
			} else {
				Breadcrumbs.hide();
			}
		});
		
		$('#breadcrumbs-sitemap, .breadcrumbs-sitemap').click(function () {
			Breadcrumbs.allow_close = false;
		});
	}
};


/* 
 * Mouse wheel jQuery plugin
 * Adds 'mousewheel' function to the objects 
 */

var mouseWheelCache = [];

$.fn.mousewheel = function (func) {
	
	return this.each(function () {
		if (!func) return this;
		var callback_func = func;
		var self = this;
		var delta = 0;

		function handle(current_delta, func)
		{
			if (typeof delta == 'undefined') delta = 0;
		  
			delta += current_delta;
			
			if (delta > 1) {
				delta = 0;
				return !(callback_func.call(self, 1));
			}
			if (delta < -1) {
				delta = 0;
				return !(callback_func.call(self, -1));
			}
			
			return true;
		}
		
		function wheel(event)
		{
			var current_delta = 0;	
			if (!event) /* For IE. */
				event = window.event;
				
			if (event.wheelDelta) { /* IE/Opera. */
				current_delta = event.wheelDelta/120;
			} else if (event.detail) { /** Mozilla case. */
				current_delta = -event.detail/3;
			}
			
			if (current_delta)
				var result = handle(current_delta, callback_func);

			if (result) {
	          if (event.preventDefault)
				event.preventDefault();
	          event.returnValue = false;
	        }
		}
		
		if (this.addEventListener)
			this.addEventListener('DOMMouseScroll', wheel, false);
	
		this.onmousewheel = wheel;
	});
};



//Validation functions
Validate = {
	//Check for non empty value
	notempty: function (v) { return (v != '' && v !== 0 && v !== null && v !== false); },
	//Length of the string/array
	length_range: function (v, min, max) { return (v.length >= min && v.length <= max); },
	//Number is in the range
	range: function (v, min, max) { v = parseInt(v); return (v >= min && v <= max); },
	//Value matches other inputs value
	match: function (v, target) { t = $('#' + target).val(); return (v == t); },
	//Regex
	regex: function (v, expression) { 
		try {
			var expr = null;
			eval('expr = ' + expression + ';');
			return expr.test(v);
		} catch (error) {
			alert('Regular expression failed: ' + error);
			return true;
		}
	},
	//Email
	email: function (v) { 
		return /^([a-zA-Z0-9\+\._\-])+@([a-zA-Z0-9+\._\-])+\.[A-Za-z]{2,6}$/.test(v); 
	},
	//Numbers only
	numeric: function (v) { return /^[0-9]+$/.test(v); },
	//Numbers and alphabet characters only
	alnum: function (v) { return /^[a-zA-Z0-9]$/.test(v); },
	//Minimum length
	min: function (v, min) { return (v.length >= min); },
	//Maximum length
	max: function (v, max) { return (v.length <= max); },
	//Minimum numberic value
	minNum: function (v, min) {
		 v = (new String(v)).replace(/^[0]+/g, '');
		 if (!v) v = 0;
		 v = parseInt(v); return (v >= min); 
	},
	//Maximum numberic value
	maxNum: function (v, max) {
		v = (new String(v)).replace(/^[0]+/g, '');
		if (!v) v = 0;
		v = parseInt(v); return (v <= max);
	}, 
	minYear: function (v, minYearValue) {v = parseInt(v); return (v >= minYearValue);} 
};

/* Initialize */

$(document).ready(function () {
	
	if ($.browser.safari) {
		$('.header-search-input input').addClass('safari');
		$('body').addClass('safari');
	}
	
	ieFixes();
	
	//Initialize send to friend
	SendToFriend.init();
	
	//Initialize language selector
	new simplePopup($('div.country-selector'), $('#header div.country a'));
	
	//Search input field default value
		var search_input = $('div.header-search-input input');
		if (search_input[0])
		{
			new EmptyInput(search_input);
		}
	
	/* Calls print screen for all links with href #print-page */
		$('a[href="#print-page"]').click(function () { window.print(); });
});
