$(document).ready(function(){
	//currentPageName = '';
	
	collections = new Array();
	collections[0] = new Array('presentation','index', 'jobs', 'news', 'contact');
	//collections[1] = new Array('index', 'jobs', 'news', 'contact');

	toPreload = new Array();
	toPreload[0] = 'altair.jpg';
	toPreload[1] = 'asphalt.jpg';
	toPreload[2] = 'bia.jpg';
	toPreload[3] = 'nova.jpg';
	toPreload[4] = 'terminator.jpg';
	toPreload[5] = 'wwg.jpg';
	
	for(var i = 0; i < toPreload.length; i++)
	{
		pic1= new Image(1280, 1194); 
		pic1.src = "../images/backgrounds/"+toPreload[i]; 
	}

	// Function to switch style in accordance to what page is beeing loaded abd actually load the page
	allowSwitch = true;
	function bindSwitch(obj)
	{
		if(allowSwitch == false)
		{
			return false;			
		}
		
		pageNameVessel = obj.getAttribute("rel");
		pageName = pageNameVessel.substring(pageNameVessel.length-4, 0);
		pageParams = obj.getAttribute("params");
		
		
		//$('#frame_center').html('');
		//$('#frame_center').css('height', '470px');
		$('#cartoon_holder_0').hide();
		$('#cartoon_holder_1').hide();
		
		currentFrameCenterHeight = $('#frame_center').outerHeight();
		
		$('#frame_center_loader').css('height', currentFrameCenterHeight);
		$('#frame_center_loader').css('width', '787px');
		$('#frame_center_loader').fadeIn(
				'slow',
				function(){
					allowSwitch = false;
					switchPage(pageName, pageParams, pageNameVessel);
				}
				);
		
		//$('.wind_bottom').hide();
		
		//switchPage(pageName, pageParams);
		return false;
	}

	// Initial bind click to pageswitch 
	$('.pageswitch').bind('click', (function()
	{
		bindSwitch(this);
		return false;
	}));
	
	// Look at # in url and load page based on that if possible
	//alert(document.location.href);
	splitUrl = document.location.href.split("#");
	//alert(splitUrl);
	
	// Initially loading index module bind and unbind clicks so that content is properly bound
	page_to_load = 'index_module';
	pageToLoadInnerHtml = $("#initial_page").html();
	if(pageToLoadInnerHtml != '' && pageToLoadInnerHtml != null)
	{
		page_to_load = pageToLoadInnerHtml;
	}
	$.post(page_to_load+".php", 
			function(data)
			{
				/*$('.frame_center').html(data);
				$('.pageswitch').unbind('click');
				$('.pageswitch').bind('click', (function()
				{
					bindSwitch(this);
					return false;
				}));*/
				pageName = page_to_load.substring(page_to_load.length-7, 0);
				pageParams = '';
				//alert("pageName: -"+pageName+"-");
				pageNameVessel = pageName+"_css";
				switchPage(pageName, pageParams, pageNameVessel);
			}
	);
	
	// Switch styles in accordance to style name that is in relation to page beeing loaded
	function switchStylestyle(styleName)
	{
		$('link[rel*=style][title]').each(function(i) 
		{
			this.disabled = true;
			if (this.getAttribute('title') == styleName) this.disabled = false;
		});
	}
	
	// Swtich the actual page using given parameters, will also rebind bindSwitch to click for new content
	function switchPage(pageName, params, pageNameVessel)
	{
		var zeParams = {};
		
		if(params != '' && params != null)
		{
			paramList = params.split('___');
			for(var i = 0; i < paramList.length; i++)
			{
				aParam = paramList[i].split('__');
				zeParams[aParam[0]] = aParam[1];
			}
		}
		else
		{	
			zeParams = { gen: "null" };
		}
		
		$.get(pageName+"_module.php", zeParams, 
				function(data)
				{
					// fetching current center frame height 
					currentHeight = $('#frame_center').outerHeight();

					//alert(currentHeight);
					//return false;
					//alert(currentHeight);
					
					if(currentHeight < 505)
					{
						currentHeight = 505;
					}
					
					// setting center frame height to a static value to avoid flicker
					$('#frame_center').css('height', currentHeight+'px');
					
					switchStylestyle(pageNameVessel);
					//alert("pageNameVessel: -"+pageNameVessel+"-");
					
					// putting new data inside center frame
					$('#frame_center').html(data);
					
					// DUMMY FRAME TEST - Disabled
					//$('#frame_center_dummy').html('');
					//$('#frame_center_dummy').html(data);
					//dummyHeight = $('#frame_center_dummy').outerHeight()
					//alert(dummyHeight);
					//$('#frame_center_dummy').html('');
					//alert($('#frame_center').innerHeight());
					//$('#frame_center').height('');
					//$('#frame_center').css('height', currentHeight+'px');
					
					$('#frame_center_loader').fadeOut(
							'slow',
							function() {
								//return false;
								//$('#frame_center_loader').css('height', '0px');
								//$('#frame_center_loader').css('width', '0px');
								//$('#frame_center').animate(
										//{"height": dummyHeight+"px"}, 1000,
										//function() {
											//alert($('#frame_center').outerHeight());
											//$('#frame_center').css('height', '');
										//}
									//);
								$('#frame_center').animate(
										{"height": "100%"}, 1000,
										function() {
											//alert($('#frame_center').outerHeight());
										}
									);
								// Select a random toon
								changeToon();
							}
						);
					
					// Unbind pageswitches
					$('.pageswitch').unbind('click');
					// Rebind pageswitches
					$('.pageswitch').bind('click', (function()
					{
						bindSwitch(this);
						return false;
					}));
					
					// Unbind form submit if page is contact
					if(pageName == 'contact')
					{
						$("#contact_form").submit(function(){  
							submitIt = true;
							//submitIt = processContactForm();
							if(!submitIt)
							{
								$("#form_message_container").attr('class', 'error_message');
								$("#form_message_container").html('Pentru a ne contacta, va rugam sa completati toate campurile formularului.');
								return false;
							}
							else
							{
								checkTick = 0;
								$("#form_div").hide();
								$("#name").attr('class', 'text');
								$("#email").attr('class', 'text');
								$("#phone").attr('class', 'text');
								$("#message").attr('class', 'text');
								//$("#captcha").attr('class', 'text');
								$("#loaderDiv").show();
								$("#form_message_container").attr('class', '');
								$("#form_message_container").html('');
								checkSubmit(); // return irrelevant, everything handled starting with checkSubmit;
							}
							$("#upload_target").html('');
							$("#contact_form").attr('target', 'upload_target');
						})
					}
					else if (pageName == 'presentation')
					{
						$('a[id*=gameloft_set]').each(function(i){
							$(this).nyroModal();
							$(this).css('color', '#FFFFFF');
						});
						$(".collectionImg").hover(
						  function () {
							$(this).fadeTo("fast", 1);
						  }, 
						  function () {
							$(this).fadeTo("fast", 0.8);
						  }
						);

					}
					
					//alert('pageName: ' + pageName);
					//alert('currentPageName: ' + currentPageName);

					//return false;
					
					if(pageName != currentPageName)
					{
						switchBanner(pageName);
					}
				}
		);
	}
	
	function switchBanner(pageName)
	{
		if(pageName == '')
		{
			return false;
		}
		
		for(var tt = 0; tt < collections.length; tt++)
		{
			if(in_array(pageName, collections[tt]) && in_array(currentPageName, collections[tt]))
			{
				return false;
			}
		}
		
		$('#bannerLoaderImg').show('fast');
		$('#flash_cont_dummy').show('fast', function()
			{
				$('#flash_cont').hide('slow', function()
					{
						$.get("banner_module.php", { "module": pageName }, 
							function(data)
							{
								$('#flash_cont').html(data);
								$('#flash_cont').show('slow', function()
									{
										$('#bannerLoaderImg').hide('fast');
										$('#flash_cont_dummy').hide('fast');
									}
								);
								currentPageName = pageName;
							}
						);
					}
				);
			}
		);
		

		
		return false;
		$('#flash_bg_temp').show('fast', 
				function ()
				{
					$('#flash_bg').hide('slow', function()
						{
							//$('#flash_bg').html('<div class="bannerLoaderImg"></div>');
							$.get("banner_module.php", { "module": pageName }, 
									function(data)
									{
										$('.flash_bg').html(data);
										currentPageName = pageName;
										$('#flash_bg').show('slow');
									}
								);
						}
					);
					
				}
			);
		
		return false;
		
		$('#flash_bg').html('');
		$('#flash_bg').html('<div class="bannerLoaderImg"></div>');
		
	}
	
	function in_array(needle, haystack)
	{
		for(var i = 0, l = haystack.length; i < l; i++) {
			if(haystack[i] == needle) {
				return true;
			}
		}
		return false;
	}
	
	function processContactForm()
	{
		// Process data to see if it's valid
		name = $("#name").attr('value');
		email = $("#email").attr('value');
		phone = $("#phone").attr('value');
		message = $("#message").attr('value');
		
		$("#name").attr('class', 'text');
		$("#email").attr('class', 'text');
		$("#phone").attr('class', 'text');
		$("#message").attr('class', 'text');
		
		//alert(name+'--'+email+'--'+phone+'--'+'--'+message);
		
		wesend = true;
		if(name == '')
		{
			$("#name").attr('class', 'text_red');
			wesend = false;
		}
		if(email == '')
		{
			$("#email").attr('class', 'text_red');
			wesend = false;
		}
		if(phone == '')
		{
			$("#phone").attr('class', 'text_red');
			wesend = false;
		}
		if(message == '')
		{
			$("#message").attr('class', 'text_red');
			wesend = false;
		}
		
		
		return wesend;
	}

	var checkTick = 0;
	function checkSubmit()
	{
		checkTick++;

		returnCode = '';
		
		var iframeDoc = $("#upload_target")[0].contentWindow.document;

		returnCode = $("#returnCode", iframeDoc).html();

		message = new Array();
		message[0] = ''; 			// the message to display
		message[1] = 'text'; 		// the type of message
		message[3] = new Array(); 	// array of fields that should be highlighted (their ids)
		
		
		if(returnCode && returnCode != '')
		{
			//alert("returnCode Found: " + returnCode);
			
			message = parseReturnCode(returnCode);
			
			raiseMessage(message);
			
			$("#returnCode", iframeDoc).html('');			
			
			checkTick = 0;
			
			$("#form_div").show();
			$("#loaderDiv").hide();
			//$("#captcha").attr('value', '');
			//$("#captcha_image").attr('src', 'securimage_show.php?sid=' + Math.random());
			
			if(message[1] == 'success_message')
			{
				$("#name").attr('value', '');
				$("#email").attr('value', '');
				$("#phone").attr('value', '');
				$("#message").attr('value', '');
			}
			
			return false;
		}
		else if(checkTick >= 61)
		{
			message[0] = 'Trimiterea a esuat din motive necunoscute. Va rugam incercati din nou.';
			message[1] = 'error_message';
			
			raiseMessage(message);
			
			$("#returnCode", iframeDoc).html('');			
			
			checkTick = 0;
			
			$("#form_div").show();
			$("#loaderDiv").hide();
			//$("#captcha").attr('value', '');
			//$("#captcha_image").attr('src', 'securimage_show.php?sid=' + Math.random());

			return false;
		}
		
		x = setTimeout(checkSubmit, 1000);
	}
	
	
	function parseReturnCode(errorCodes)
	{
		// element 0 is the message
		// element 1 is the message type  (ERROR or SUCCESS)
		message = new Array();
		message[0] = ''; // the message to display
		message[1] = 'text'; // the type of message
		message[3] = new Array(); // array of fields that should be highlighted (their ids)
		
		problemFields = new Array();
		
		errorCodesArray = errorCodes.split('|');
		//alert(errorCodesArray);
		errorCodesArrayLength = errorCodesArray.length-1; // without last element, that is always 0
		
		var jj = 0;
		for(var i=1; i < (errorCodesArrayLength); i++) // first element always 0;
		{
			//alert(errorCodesArray[i]);
			errRelatedData = fetchErrRelatedData(errorCodesArray[i]);
			message[0] = message[0] + errRelatedData[0] + '<br/>';
			message[3][jj] = errRelatedData[1];
			jj++;
		}
		//alert('message[0]: ' + message[0]);
		if(message[0] == '')
		{
			//alert('parseReturnCode NOERRORS');
			message[0] = 'Mesajul dumneavostra a fost trimis.';
			message[1] = 'success_message';
		}
		else
		{
			message[1] = 'error_message';
		}
		
		//alert('parseReturnCode message: ' + message)
		
		return message;
	}
	
	function isArray(obj)
	{
	   if (obj.constructor.toString().indexOf("Array") == -1)
		  return false;
	   else
		  return true;
	}	

	function fetchErrRelatedData(code)
	{
		// index 0 - error message
		// index 1 - related field
		errRelatedData = new Array();
		switch(code)
		{
			case '55500001': // Phone number not valid or missing;
					errRelatedData[0] = 'Numar de telefon lipsa sau invalid.'
					errRelatedData[1] = 'phone';
					break;
			case '55500002': // Email not valid or missing;
					errRelatedData[0] = 'Adresa de email lipsa sau invalida.'
					errRelatedData[1] = 'email';
					break;
			case '55500003': // Missing name;
					errRelatedData[0] = 'Nume lipsa.'
					errRelatedData[1] = 'name';
					break;
			case '55500004': // Missing Message;
					errRelatedData[0] = 'Mesaj lipsa.'
					errRelatedData[1] = 'message';
					break;
			case '77700001': // File type not allowed;
					errRelatedData[0] = 'Tip de fisier nepermis.'
					errRelatedData[1] = 'cv';
					break;
			case '77700002': // File too big; (max 2Mb)
					errRelatedData[0] = 'Fisier atasat este prea mare. (max. 3Mb)'
					errRelatedData[1] = 'cv';
					break;
			case '99900001': // Captcha missing or wrong
					errRelatedData[0] = 'Cod de verificare gresit.'
					errRelatedData[1] = 'captcha';
					break;
			default: // Unkown
					errRelatedData[0] = ''
					errRelatedData[1] = '';
		}
		
		//alert(errRelatedData);
		
		return errRelatedData;
	}
	
	function raiseMessage(message)
	{
		$("#form_message_container").attr('class', message[1]);
		$("#form_message_container").html(message[0]);
		
		messageFieldsLength = message[3].length
		for(var ii = 0; ii < messageFieldsLength; ii++)
		{
			$("#"+message[3][ii]).attr('class', 'text_red');
		}
	}
	
	var backgroundTicker = 0; // used to determine if it's time to change the background
	var current_bg_layer = '1';
	var current_toon_layer = '1';
	var timer_is_on = 0;

	function changeBack()
	{
		//alert(backgroundTicker);
		if(backgroundTicker == 1)
		{
			if(current_bg_layer == '1')
			{
				next_bg_layer = '0';
			}
			else
			{
				next_bg_layer = '1';
			}
			
			//alert(current_bg_layer);
			//alert(next_bg_layer);
			
			var availableBackgrounds = new Array( );
			availableBackgrounds[0] = 'background_box_altair';
			availableBackgrounds[1] = 'background_box_altair';
			availableBackgrounds[2] = 'background_box_nova';
			availableBackgrounds[3] = 'background_box_asphalt';
			availableBackgrounds[4] = 'background_box_nova';
			availableBackgrounds[5] = 'background_box_terminator';
			availableBackgrounds[6] = 'background_box_bia';
			availableBackgrounds[7] = 'background_box_wwg';
			availableBackgrounds[8] = 'background_box_nova';
			availableBackgrounds[9] = 'background_box_bia';
			availableBackgrounds[10] = 'background_box_nova';
			availableBackgrounds[11] = 'background_box_bia';
			availableBackgrounds[12] = 'background_box_nova';
			availableBackgrounds[13] = 'background_box_bia';
			availableBackgrounds[14] = 'background_box_nova';
			availableBackgrounds[15] = 'background_box_bia';

			currentBack = $("#background_box_"+current_bg_layer).attr('class');
			currentBack = currentBack.split(' ');
			currentBack = currentBack[1];
			
			var backIndex = Math.floor(Math.random() * 16);
			
			//alert(currentBack);
			//return false;
			//alert(backIndex);
			
			while(availableBackgrounds[backIndex] == currentBack)
			{
				var backIndex = Math.floor(Math.random() * 16);
			}
			
			$("#background_box_"+next_bg_layer).attr('class', 'background_box '+availableBackgrounds[backIndex]);
			
			$("#background_box_"+current_bg_layer).fadeOut('slow');
			$("#background_box_"+next_bg_layer).fadeIn('slow');

			if(current_bg_layer == '1')
			{
				current_bg_layer = '0';
			}
			else
			{
				current_bg_layer = '1';
			}
			
			//alert(current_bg_layer);
			//alert(next_bg_layer);
		
		}
		else
		{
			backgroundTicker = 1;
		}
		
		t = setTimeout(changeBack, 20000);
	}	
	
	function doNothing()
	{
		//alert('a');
		return true;
	}

	function bgTimer()
	{
		if (!timer_is_on)
		{
			timer_is_on=1;
			changeBack();
		}
	}
	
	bgTimer();
	
	function changeToon()
	{
		if(current_toon_layer == '1')
		{
			next_toon_layer = '0';
		}
		else
		{
			next_toon_layer = '1';
		}
		
		var availableToons = new Array( );
		availableToons[0] = 'cartoon_guy';
		availableToons[1] = 'cartoon_blonde';
		
		var availableToonsImgs = new Array( );
		availableToonsImgs[0] = 'blonde.png';;
		availableToonsImgs[1] = 'guy.png';
		
		var toonIndex = Math.floor(Math.random() * 2);
		
		$("#cartoon_holder_"+next_toon_layer).attr('class', availableToons[toonIndex]);
		$("#cartoon_img_"+next_toon_layer).attr('src', 'images/cartoons/'+availableToonsImgs[toonIndex]);
		
		$("#cartoon_holder_"+current_toon_layer).fadeOut('fast');
		$("#cartoon_holder_"+next_toon_layer).fadeIn(
				'fast', 
				function()
				{
					allowSwitch = true;
				}
			);
		
		if(current_toon_layer == '1')
		{
			current_toon_layer = '0';
		}
		else
		{
			current_toon_layer = '1';
		}
	}
	
	// Call the hash checker (that can trigger page change based on hash)
	//setInterval ( "hashProcess()", 1000 );
})

function showMore(id, prefix, page)
{
	acutalElementToShow = prefix + '_' + id;
	moreOrLessSpan = 'more_or_less_'+id;
	plusMinusIco = 'plus_minus_'+id;
	
	//alert(plusMinusIco);
	
	plusMinusIco_currentSrc = $("#"+plusMinusIco).attr('src');
	plusMinusIco_newSrc_pTOm = plusMinusIco_currentSrc.replace("plus.png", "minus.png")
	plusMinusIco_newSrc_mTOp = plusMinusIco_currentSrc.replace("minus.png", "plus.png")
	
	moreOrLessSpan_currentText = $("#"+moreOrLessSpan).html();

	// When user clicked to see less for a certain article, clsoing article and returning;
	if(moreOrLessSpan_currentText == 'mai putin')
	{
		$("#"+acutalElementToShow).hide('fast');
		$("#"+plusMinusIco).attr('src', plusMinusIco_newSrc_mTOp);
		$("#"+moreOrLessSpan).html('mai mult');
		return false;
	}

	// Hiding all articles
	$('span[id*='+prefix+']').each(function(i){
		//alert(i);
		$(this).hide('fast');
		$('span[id*=more_or_less]').each(function(i){
			$(this).html('mai mult');
		});
	});

	// switching all icos
	$('img[id*=plus_minus]').each(function(i){
			$(this).attr('src', plusMinusIco_newSrc_mTOp);
	});
	
	// showing selected article
	$("#"+acutalElementToShow).css('display', 'block');
	$("#"+acutalElementToShow).hide();
	$("#"+acutalElementToShow).fadeIn('slow');
	//alert(acutalElementToShow);
	$("#"+moreOrLessSpan).html('mai putin');
	$("#"+plusMinusIco).attr('src', plusMinusIco_newSrc_pTOm);
	
	return false;
}

function hashProcess()
{
	//splitUrl = document.location.href.split("#");

	//pages = new Array('index', 'jobs', 'news', 'contact');
	
	//document.getElementById();
	//alert(splitUrl);
}