var eroriAJAX = '';
var currentString = '';
var key = 'pagina';

function externalLinks ()
{
	$("a[rel*='external']").attr('target','_blank');
}

function atribuieHash ( value ) {
	var s = window.location.hash;
	if ( s.indexOf( key + '=' ) != -1 ) {
		var re = new RegExp( "(?=" + key + "=)[^&]+" );
		s = s.replace( re, key + '=' + encodeURIComponent( value ) );
	}
	else {
		if ( s.length == 0 ) {
			s = key + '=' + encodeURIComponent( value );
		}
		else {
			s = s.concat( '&' + key + '=' + encodeURIComponent( value ) );
		}
	}
	window.location.hash = s;
	currentString = s;
	return false;
}

function iaHash () {
	var s = window.location.hash;
	if ( s.indexOf( key ) == -1 )
	{
		return false;
	}
	var re = new RegExp( "(?=" + key + "=)[^&]+" );
	s = s.match( re );
	return decodeURIComponent( s[0].substring( key.length + 1, s[0].length ) );
}

function eliminaHash () {
	window.location.hash = '';
	currentString = '';
	return false;
}

function randomStart() {
	var x = Math.ceil( Math.random() * 10 ) % 3 + 1;
	if ( x > 1 )
	{
		$('#t'+x).click();
	}
}

function hashStart () {
	var deAratat = iaHash();
	var aratatDeja = false;
	$('#t-despre .localFooter a').each( function () {
		if ( $(this).attr('href').substring(1) == deAratat )
		{
			var target = $('#t-'+deAratat);
			if ( target.text().length )
			{
				$('#main').hide();
				$('#aside').show();
				target.show();
				$('#meniu li').removeClass('Active');
				if ( $('li#'+deAratat).text().length )
				{
					$('li#'+deAratat).addClass('Active');
				}
				aratatDeja = true;
				return false;
			}
		}
	});
	if ( !aratatDeja )
	{
		$('#catalog li ul a').each( function () {
			if ( $(this).attr('href').substring(1) == deAratat )
			{
				/*
				if ( $(this).attr('href').substr(3,6) == 'manusa' ) var caut = 't1';
				else if ( $(this).attr('href').substr(3,6) == 'coarda' ) var caut = 't2';
				else if ( $(this).attr('href').substr(3,6) == 'accesr' ) var caut = 't3';
				$('#flowtabs a[id="'+caut+'"]').click();
				*/
				$('#main').hide();
				$('#aside').show();
				$('#'+deAratat).show();
				$('#catalog li').removeClass('Active');
				$(this).parent().addClass('Active');
				aratatDeja = true;
				return false;
			}
		});
	}
	if ( !aratatDeja )
	{
		$('#flowtabs a').each( function () {
			if ( $(this).attr('href').substring(1) == deAratat )
			{
				$(this).click();
				aratatDeja = true;
				return false;
			}
		});
	}
}

function navigationEnhancement () {

	$("a[href^='#']").click(function () {
		var locatie = $(this).attr('href').substring(1);
		if ( locatie != '' && $(this).parent().parent().attr('id') != 'flowtabs' ){
			$('html,body').animate({scrollTop: 0}, 500);
		}
		return false;
	});

	$("#flowpanes").scrollable( {
		size: 1,
		hoverClass: 'hover',
		clickable: false
	}).circular().navigator( {
		navi: "#flowtabs",
		naviItem: 'a',
		activeClass: 'Active'
	}).autoscroll({
		autoplay: false,
		steps: 1,
		interval: 10000
	});
	
	$('#flowtabs a').click( function () {
		var tab = $(this).attr('href').substring(1);
		if ( !$('#catalog-'+tab).is(':visible') )
		{
			$('#catalog li.Categorie').hide();
			$('#catalog-'+tab).fadeIn(500);
		}
		atribuieHash(tab);
	});
	
	$('#catalog li ul a').click( function () {
		var deAratat = $(this).attr('href').substring(1);
		if ( !$('#main').is(':hidden') )
		{
			$('#main').fadeOut(500, function () {
				$('#aside').show();
				$('#'+deAratat).fadeIn(500);
			});
		}
		else
		{
			$('#aside div[id^="t-"]:visible').hide();
			$('#'+deAratat).fadeIn(500);
		}
		$('#catalog li').removeClass('Active');
		$(this).parent().addClass('Active');
		atribuieHash(deAratat);
		return false;
	});

	$('#aside a[href="#pagina=contact"]').click( function () {
		if ( !$('#main').is(':hidden') )
		{
			$('#main').fadeOut(500, function () {
				$('#aside').show();
				$('#t-contact').fadeIn(500);
				$('#meniu li').removeClass('Active');
				$('#meniu li#contact').addClass('Active');
			});
		}
		else
		{
			$('#aside div[id^="t-"]:visible').hide();
			$('#t-contact').fadeIn(500);
			$('#meniu li').removeClass('Active');
			$('#meniu li#contact').addClass('Active');
		}
		atribuieHash('contact');
	});

	$('#meniu a,#concluzie a').click( function () {
		var listItem = $(this).parent();
		var deAratat = listItem.attr('id');
		var target = $('#t-'+deAratat);
		if ( target.text().length )
		{
			if ( !$('#main').is(':hidden') )
			{
				$('#main').fadeOut(500, function () {
					$('#aside').show();
					target.fadeIn(500);
					$('#meniu li').removeClass('Active');
					listItem.addClass('Active');
				});
			}
			else
			{
				$('#aside div[id^="t-"]:visible').hide();
				target.fadeIn(500);
				$('#meniu li').removeClass('Active');
				listItem.addClass('Active');
			}
			atribuieHash(deAratat);
		}
		return false;
	});
	
	$('.localFooter a').click( function () {
		var deAratat = $(this).attr('href').substring(1);
		var target = $('#t-'+deAratat);
		if ( target.text().length )
		{
			$('#aside div[id^="t-"]:visible').hide();
			target.fadeIn(500);
			$('#meniu li').removeClass('Active');
			if ( $('li#'+deAratat).text().length )
			{
				$('li#'+deAratat).addClass('Active');
			}
			atribuieHash(deAratat);
		}
		return false;
	});

	$('a#branding,a.InchideAside,li#acasa a').click( function () {
		if ( $('#main').is(':hidden') )
		{
			$('#aside,#aside div[id^="t-"]:visible').hide();
			$('#main').fadeIn(500);
			$('#meniu li').removeClass('Active');
			$('html,body').animate({scrollTop: 0}, 500);
			$('#catalog li').removeClass('Active');
			eliminaHash();
		}
		return false;
	});

}

function effectsEnhancement () {

	$('#overlay').fadeTo(1,0.6);
	
	if ( jQuery.browser.msie && parseInt(jQuery.browser.version) == 6 ) {
		$(function() {
			$('button,input,select,textarea,li,button').hover(function() {
				$(this).addClass('hover');
			}, function() {
				$(this).removeClass('hover');
			});
			$('button,input,select,textarea,button').focus(function() {
				$(this).addClass('focus');
			});
			$('button,input,select,textarea,button').blur(function() {
				$(this).removeClass('focus');
			});
		});
	}
	
	$('#aside,#aside div[id^="t-"]').hide();
	$('#catalog li.Categorie').hide();
	$('#catalog li.Categorie:first-child').show();
	
	$('#concluzie li a').css('box-shadow','0px 2px 3px #999').css('-moz-box-shadow','0px 2px 3px #999').css('-webkit-box-shadow','0px 2px 3px #999');
	$('#catalog a .Thumb').css('border-radius','5px').css('-moz-border-radius','3px').css('-webkit-border-radius','3px');
	$('#catalog ul a:hover .Thumb').css('box-shadow','0px 2px 2px #bbb').css('-moz-box-shadow','0px 2px 2px #bbb').css('-webkit-box-shadow','0px 2px 2px #bbb');

	$('.Alternate').hide();
	$('#aside .ColoanaStanga').hover( function () {
		if ( $(this).find('img.Alternate').length )
		{
			$(this).find('.Normal').hide();
			$(this).find('.Alternate').fadeIn('500');
		}
	}, function () {
		if ( $(this).find('img.Alternate').length )
		{
			$(this).find('.Normal').fadeIn('500');
			$(this).find('.Alternate').hide();
		}
	});
	
	$('a#emailLink').click( function () {
		$(this).attr('href','ma'+'ilto'+':conta'+'ct@'+'suplim'+'ente.'+'ro');
		return true;
	});
	
	if ( !iaHash() )
		setTimeout("randomStart();",500);
	else
		setTimeout("hashStart();",500);
}

function flashEroare ( daSauNu ) {
	if ( daSauNu )
	{
		var t = setTimeout("$('.Proces').slideUp('1000')",6000);
		var locatieLead = String(location.href);
		if ( locatieLead.charAt( locatieLead.length - 1 ) == '/' ) locatieLead = locatieLead.substring( 0, locatieLead.length - 2 );
		if ( pageTracker && pageTracker != 'undefined' ) 
		{
			try { pageTracker._trackPageview( locatieLead + "/contact/" ); } catch(err) {}
		}

		$('#mesaj').val('');
		$('#eroare').val(eroriAJAX);
	}
	else
	{
		$('.Proces').slideDown(1000, function () {
			var a = $('.Proces .Attention');
			a.fadeOut(300, function () { a.fadeIn(300, function () { a.fadeOut(300, function () { a.fadeIn(300, function () { a.fadeOut(300, function () { a.fadeIn(300) } ) } ) } ) } ) } );
		});
	}
}

function inputEnhancement () {

	var regexMail = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	var regexPhone = /^[0-9]{10}$/;
	$('#leadForm').submit(function() {

		var deTrimis = true;
		var focusedObj = false;
	
		$(this).find('input:visible,textarea:visible').each( function () {
			var parinte = $(this).parent();
			parinte.removeClass('Error');
			var inputObj = $(this);
			var conditii = ( inputObj.val() == '' || inputObj.val() == 'null' || inputObj.val() == undefined || inputObj.val().length < 2 ||
				( inputObj.attr('id') == 'telefon' && !regexPhone.test(inputObj.val()) ) ||
				( inputObj.attr('id') == 'mail' && !regexMail.test(inputObj.val()) ) );
			if ( conditii )
			{
				parinte.addClass('Error');
				if ( !focusedObj )
				{
					$(this).focus();
					focusedObj = true;
				}
				deTrimis = false;
			}
		});
		
		if ( !deTrimis )
		{
			alert('Completeaza din nou campurile inrosite!');
		}
		else
		{
			$(this).find('input,textarea').parent().removeClass('Error');
			$('.Proces').html('<h4>Multumim!</h4><img src="http://harbinger.ro/img/loader.gif" width="16" height="16" alt="Te rugam sa astepti..." /><p class="Loading">Formularul se trimite...</p>');
			if ( $('.Proces').is(':hidden') ) $('.Proces').fadeIn(100);
			$.ajax({
				type: "GET",
				url: "lead.php",
				async: true,
				cache: false,
				data: ({
					nume: $('#nume').val(),
					mail: $('#mail').val(),
					telefon: $('#telefon').val(),
					mesaj: $('#mesaj').val(),
					locatieURL: $('#locatieURL').val(),
					ref: $('#ref').val(),
					datasent: 'true',
					tech: 'ajax'
				}),
				dataType: "text",
				timeout: 10000,
				beforeSend: function (XMLHttpRequest) {
					$('.Proces').fadeOut( 200 );
				},
				complete: function (XMLHttpRequest, textStatus) {
					$('#lead').html(XMLHttpRequest.responseText);
					$('.Proces').fadeIn(500);
				}
			});
		}
		return false;
	});

}

function startMap () {

	function onSmartWinEvent() {
		var words = "<div><strong>Sediul Suplimente.ro</strong><br /><span>importatorul oficial al produselor Harbinger</span></div>";
		marker.openSmartWindow(words);
	}

	var map = new YMap(document.getElementById('map'));
	var myPoint = new YGeoPoint(44.42119,26.10642);

	//map.addTypeControl();
	map.addZoomLong();
	//map.addPanControl();
	map.disableKeyControls();
	map.removeZoomScale();
	map.setMapType(YAHOO_MAP_REG);
	map.drawZoomAndCenter(myPoint, 4);
	
	var dimensiuniHarta = new YSize(420,220);
	map.resizeTo(dimensiuniHarta);

	var marime = new YSize(129,47);
	var imagine = new YImage('http://harbinger.ro/img/bubble.png', marime);

	var marker = new YMarker(myPoint,imagine);
	//marker.addLabel("Suplimente.ro");
	//YEvent.Capture(marker, EventsList.MouseClick, onSmartWinEvent);
	map.addOverlay(marker);

}

window.onload = setScreenClass; 
window.onresize = setScreenClass;

function setScreenClass ()
{
	//	class name			screen width
	//	------------------------------------------
	//	handheld			240px	-	479px
	//	small				480px	-	1067px
	//	standard			1068px	-	1280px
	//	wide				1281px	-	infinit

	var fmt = document.documentElement.clientWidth;
	var cls = (fmt<=479)?'handheld':(fmt>479&&fmt<=1067)?'small':(fmt>1067&&fmt<=1280)?'standard':'wide';
	document.body.className = cls;
}

$(document).ready(function () {

	// Navigare imbunatatita cu efecte
	navigationEnhancement();

	// Input-uri
	inputEnhancement();

	// Opacitati si efecte
	effectsEnhancement();

	// Link-uri externe
	externalLinks();
	
	// Harta Yahoo
	startMap();

	// Setarile de AJAX
	$.ajaxSetup( {
		error : function( x, e ) {
			if( x.status == 0 ) {
				eroriAJAX += 'Conexiunea ta este intrerupta!\n E posibil sa ai probleme cu netul.';
			} else if( x.status == 404 ) {
				eroriAJAX += 'Nu am gasit fisierul cerut.';
			} else if( x.status == 500 ) {
				eroriAJAX += 'Eroare interna a serverului.';
			} else if( e == 'parsererror' ) {
				eroriAJAX += 'Eroare.\nNu am reusit sa parsam JSON-ul.';
			} else if( e == 'timeout' ) {
				eroriAJAX += 'Cererea a durat prea mult.';
			} else {
				eroriAJAX += 'Eroare necunoscuta.\n' + x.responseText;
			}
		}
	});

});