/*--------REZA------------*/

//initialize after images are loaded:
jQuery(window).load(function(){
	//initialization:
	if($j('#main_cont > div.sub_left').length > 0)
		makeEqualHeight();
	cornerSet();
});

/*======================DOM-READY=================================*/
jQuery(document).ready(function(){
	//initialization:
	inputFocusBlur('orgForm');
	clearFormByRefresh();
	
	if( (!($j.browser.msie && $j.browser.version <7)) && $j('#main_cont > div.sub_left').length > 0)
		makeEqualHeight();
	
	$j('ul.drawer').each(function(el,ab){
		$j(this).children('li:first').addClass('current').children('h3').addClass('first').next('div.drawerToggle').show();
		$j(this).children('li:last').children('h3').addClass('last');
	});
	
	/*//check agreed:
	if( $j("form span.checkbox input[name='cons_agreed']").length > 0)
		$j("form input[type='submit'][name='ACTION_SUBMIT_SURVEY_RESPONSE']").addClass("disabled").attr('disabled','disabled');
	*/
	
	if($j.browser.msie && $j.browser.version <7 ){
		$j("form input.butnSubmit[type='submit']").hover(
			function(){ $j(this).css({'backgroundPosition':'left bottom'}) },
			function(){ $j(this).css({'backgroundPosition':'left top'}) }
		);
	}
	//reset button:
	$j('form input:reset').click(function(){
		$j('form .mandatoryErr').removeClass('mandatoryErr');
	});
	
	//reset each load:
	$j(".login_box input:text, .login_box input:password").val('');
	
	//on comment page, delete empty reply button:
	$j("ol#commentlist div.reply").not(":contains('Reply')").remove();
	
	//nav-top mouseover:
	$j('ul#top_nav > li').hover(
		function(){$j(this).find('ul').stop(true,true).slideDown('fast')},
		function(){$j(this).find('ul').slideUp('fast')}
	);
	
	//which is at top? login/register:
	$j('.login_box').children().click(function(){
		$j(this.parentNode).children().not(this).css('z-index', '');
		$j(this).css('z-index', '10');
	});
	
	//theme switcher:
	var theme = new Array();
	$j('#color_box b').click(function(){
		$j(this).queue(function(){
			cornerUnset();
			theme = $j(this).find('img').attr('alt').split(" ", 1);
			$j(this).queue(function(){
				$j('body').attr('class',theme[0]); //addClass(theme[0]);
				cornerSet();
				saveTheme(theme);
				$j(this).dequeue();
			});
			$j(this).dequeue();
		});
	});
	
	//tabs click events:
	/*$j('ul.tabs > li').each(function(index){
		$j(this).click(function(){
			if(!$j(this).hasClass('current')){
				$j('ul.tabs > li').removeClass('current').uncorner().eq(index).addClass('current').corner("top 5px");
				$j('ul.tab_list > li').fadeOut().eq(index).fadeIn();
			}
		});
	});*/
	
	//drawer accordion:
	var oldItem, newItem;
	$j('ul.drawer > li > h3').bind("mouseover",function(){
		//dont allow multiple hover at a time:
		if (! $j(this.parentNode).hasClass('current')){
			$j(this.parentNode.parentNode).children('li').children('div.drawerToggle').stop(true,true);
			
			//store items:
			newItem = $j(this.parentNode);
			oldItem = $j(this.parentNode.parentNode).children('li.current');
			var itemHeight = oldItem.children('div.drawerToggle').outerHeight();
			
			//how animate/hide/show:
			newItem.addClass('current')
				.children('div.drawerToggle')
				.animate({
					height: itemHeight
				},{
					step:function(n, fx){
						newItem.children('div.drawerToggle').height(itemHeight - n);
					},
					duration:'slow',
					complete:function(){}
				});
			
			oldItem.removeClass('current')
				.children('div.drawerToggle')
				.animate({
					height:'hide'
				},{
					step:function(n, fx){
						newItem.children('div.drawerToggle').height(itemHeight - n);
					},
					duration:'slow',
					complete:function(){}
				});
			
			//last header should be curved or not:
			$j(this).hasClass('last')? $j(this).uncorner() : $j(this.parentNode).nextAll('li').children('h3.last').corner("bottom 5px");
		}
	});
	
});


//window popUp:
function windowPop(theURL,winName,features){window.open(theURL,winName,features)}

function forgotPassMP(index){
	if(index==0){
		$j('#logInForm').fadeOut('slow');
		$j('#forgotForm').fadeIn('slow');
	}
	else if(index==1){
		$j('#forgotForm').fadeOut('slow');
		$j('#logInForm').fadeIn('slow');
	}
}

/*======================INITIALIZATION=================================*/
function makeEqualHeight(){
	//get the heights:
	var topLft = $j('#cont_left').outerHeight();
	var topRgt = $j('#cont_rgt').outerHeight();//alert('TL:'+topLft+'; TR:'+topRgt);
	
	//get longest height:
	var reSetHeight = 0, greatestHeight = (topLft < topRgt)? topRgt : topLft; 
	
	//Left is longer :: fix right side to be equal:
	if(topLft > topRgt){
		$j('#cont_rgt > *:last').after('<div class="fillEmptyPlace">&nbsp;</div>').queue(function(){
			reSetHeight = greatestHeight - $j('#cont_rgt > div.fillEmptyPlace').offset().top -26 ; // "16+10" as "padding";
			//make even number for ie6 bug:
			if($j.browser.msie && $j.browser.version <7 ){
				reSetHeight += (reSetHeight%2);
				$j('#cont_rgt > div.fillEmptyPlace').css('height',reSetHeight+'px');
			}
			else
				$j('#cont_rgt > div.fillEmptyPlace').css('min-height',reSetHeight+'px');
			$j(this).dequeue();
		});
		
		//recalculate:
		topRgt = $j('#cont_rgt').outerHeight();
		greatestHeight = (topLft < topRgt)? topRgt : topLft;
	}
	
	//Right is longer :: fix left side to be equal:
	if(greatestHeight!=0){
		//reset height as difference:
		reSetHeight = greatestHeight - $j('#main_cont > *:first').offset().top-26;
		//make even number for ie6 bug:
		if($j.browser.msie && $j.browser.version <7 ){
			reSetHeight += (reSetHeight%2);
			$j('#main_cont > *').css('height',reSetHeight+'px');
		}
		else
			$j('#main_cont > *').css('min-height',reSetHeight+'px');
	}
}

/*======================COOKIE=================================*/
function setCookie(cookieName, value, expiredays){
	var ExpireDate = new Date ();
	ExpireDate.setTime(ExpireDate.getTime() + (expiredays * 24 * 3600 * 1000));
	document.cookie = cookieName + "=" + escape(value) +
	((expiredays == null) ? "" : "; expires=" + ExpireDate.toGMTString())+ "; path=/";
}
		  
// retrieve the values of cookie display property from cookie
function getCookie(cookieName)  {
	if (document.cookie.length > 0)	{
		begin = document.cookie.indexOf(cookieName+"=");
		if (begin != -1) {
			begin += cookieName.length+1;
			end = document.cookie.indexOf(";", begin);
			if (end == -1) end = document.cookie.length;
			return unescape(document.cookie.substring(begin, end)); 
		}
	}
	return null;
}

/*function Delete_Cookie( cookieName, path, domain ) {
	alert(1);
	document.cookie = cookieName + "=" +
	( ( path ) ? ";path=" + path : "") +
	( ( domain ) ? ";domain=" + domain : "" ) +
	";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}
Delete_Cookie('matthews-theme', '', '');*/

function saveTheme(themeName){
	setCookie('matthews-theme', themeName, 20);
}



/*======================CORNERS=================================*/
function cornerSet(){
	//rounded corners [4-side]:
	$j('#cont_rgt > *, #cont_left > *, #main_cont > *, .register_boxIn, #banner a, #footer').not('#main_cont, div.login_box, span#color_box, ul.drawer .register_boxIn').corner("5px");
	
	//rounded corners [top]:
	$j('ul.drawer > li > h3.first').corner("top 5px");
	
	//rounded corners [bottom]:
	$j('ul.drawer > li > h3.last').corner("bottom 5px");
	
	$j('div.login_box .logInner').not('ul.drawer .logInner').corner("tl tr bl 5px");
}
function cornerUnset(){
	$j('#cont_rgt > *, #cont_left > *, #main_cont > *, .register_boxIn, #banner a, #footer').not('#main_cont, div.login_box, span#color_box, ul.drawer .register_boxIn').uncorner();
	$j('ul.drawer > li > h3.first, ul.drawer > li > h3.last').uncorner();
	$j('div.login_box .logInner').not('ul.drawer .logInner').uncorner();
}




/*===================MAKE POPUP========================*/
function makePopup(id){
	$j('#prv_subject').text( $j('form#'+id+' #subject').val() );
	$j('.prv_name').text( $j('form#'+id+' #cons_first_name').val() +' '+ $j('form#'+id+' #cons_last_name').val() );
	$j('#prv_email').text( $j('form#'+id+' #cons_email').val() );
	$j('#prv_msg').text( $j('form#'+id+' #message').val() );
	
	tb_show('', $j('form input#taf_popup_preview').attr('alt'));
	return false;
}

//==============::FORM VALIDATIONs::====================
function clearFormByRefresh(){
	$j("form *[value='Please complete the field'], input[value='Please enter a valid Email address']").val('');
}

var onFocusVal='';
function inputFocusBlur(cls){
	$j('form.'+cls+' input:text, form.'+cls+' input:password, form.'+cls+' textarea')
		.focus(function(){
			$j(this).addClass('focused');
			if($j(this).hasClass('mandatoryErr') && (this.value.indexOf('We Really Need')!=-1 || this.value.indexOf('Please complete the field')!=-1 || this.value.indexOf('Please enter a valid Email address')!=-1 || this.value.indexOf('Please insert the image-code')!=-1)){
				onFocusVal=$j(this).val();
				$j(this).val('');
			}
		})
		.blur(function(){
			$j(this).removeClass('focused');
			if($j(this).hasClass('mandatoryErr') && $j(this).val()==''){
				$j(this).val(onFocusVal);
			}
		});
}

function checkEmail(email){
	var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
	if(filter.test(email)) return true; else return false;
}

function checkdependency(targetIds, disableTargets, dependsOn, theKey){
	if(theKey==dependsOn){
		//Enable as the disableTargets are dependent:
		$j(disableTargets.toString()).removeAttr('disabled');
		
		//Add mandatory:
		$j(targetIds.toString()).parent().addClass('mandatory');
		
		//Set Error MSG:
		if($j('.mandatoryErr').length){
			$j(targetIds.toString()).addClass('mandatoryErr');
			$j(disableTargets.toString()).addClass('mandatoryErr');
			
			$j(targetIds.toString()).each(function(){
				if( $j(this).attr('type').toUpperCase() == 'TEXT' || this.tagName.toUpperCase() == 'TEXTAREA' ){
					this.value='Please complete the field';
				}
			});
		}
	}
	else{
		//Disable as the disableTargets are not dependent:
		$j(disableTargets.toString()).attr('disabled','disabled').removeClass('mandatoryErr');
		$j(targetIds.toString()).each(function(){
			if( this.value=='Please complete the field' && ( $j(this).attr('type').toUpperCase() == 'TEXT' || this.tagName.toUpperCase() == 'TEXTAREA' ) ){
				this.value='';
			}
		});
		
		//Remove mandatory:
		$j(targetIds.toString()).removeClass('mandatoryErr').parent().removeClass('mandatory');
	}
}


function getAge(bDay){
	now = new Date()
	bD = bDay.split('/');
	if(bD.length==3){
		born = new Date(bD[2], bD[1]*1-1, bD[0]);
		years = Math.floor((now.getTime() - born.getTime()) / (365.25 * 24 * 60 * 60 * 1000));
		return years;
	}
}

/*onclick="submitActivation(this,this.form['ACTION_SUBMIT_SURVEY_RESPONSE'],register_form)"*/
function submitActivation(_this,target){
	if(_this.checked){
		target.disabled=false;
		$j(target).removeClass("disabled");
	}
	else{
		target.disabled=true;
		$j(target).addClass("disabled");
	}
}

function chkValidity(id, specialID){
	var formName = document.getElementById(id);// alert(id);
	var reqFields		= $j('form#'+id+' span.mandatory input, #'+id+' span.mandatory select, #'+id+' span.mandatory textarea');
	var emailField		= $j("form#"+id+" span.mandatory label:contains('Email')").parent().find("input:text");
	var captchaField	= $j("form#"+id+" span.captcha input:text");
	var maxlenFields	= $j("form#"+id+" span.maxlength input");
	var passwordFields	= $j("form#"+id+" span.text input:password");
	var agreed			= $j("form#"+id+" span.checkbox input[name='cons_agreed']");
	var err=false;
	
	//check for empty fields:
	for(i=0; i < reqFields.length; i++){ // ERR = NULL or ERR_MSG or DEFAULT_SELECT
		if( reqFields[i].value=='' || (reqFields[i].value==0 && reqFields[i].tagName.toUpperCase()=='SELECT') ){
			err=true;
			if( $j(reqFields[i]).attr('type') == 'file' )
				alert("Please upload a file.");
			else if( reqFields[i].tagName.toUpperCase() == 'SELECT' ){
				//do nothing here
			}
			else
				reqFields[i].value='Please complete the field';
			$j(reqFields[i]).addClass('mandatoryErr');
		}
		else if(reqFields[i].value.indexOf('Please complete the field')!=-1 || reqFields[i].value.indexOf('Please enter a valid Email address')!=-1 || reqFields[i].value.indexOf('Please insert the image-code')!=-1 || reqFields[i].value.indexOf('Day')!=-1 || reqFields[i].value.indexOf('Month')!=-1 || reqFields[i].value.indexOf('Year')!=-1) err=true;
		else $j(reqFields[i]).removeClass('mandatoryErr');
	}
	if(err) return false;
	
	//check valid email:
	if(emailField.length > 0){
		if( !checkEmail( emailField.val() ) ){
			emailField.addClass('mandatoryErr').val('Please enter a valid Email address');
			return false;
		}
	}
	
	//check valid maxlen (5 to max):
	for(i=0; i < maxlenFields.length; i++){
		if( !(5 <= maxlenFields[i].value.length && maxlenFields[i].value.length <= $j(maxlenFields[i]).attr('maxlength')) ){
			err=true;
			$j(maxlenFields[i]).addClass('mandatoryErr');
		}
	}
	if(err) return false;
	
	//check for equal passwords:
	if( passwordFields.length > 1 && passwordFields[0].value != passwordFields[1].value ){
		$j(passwordFields).addClass('mandatoryErr');
		alert('Insert same password.');
		return false;
	}
	
	
	//if captcha field exist:
	if(captchaField.val()!= undefined){
		$j.ajax({
			type: "POST",
			url: pluginPath+"/wp-esa-contest/ajax.php",
			data: 'text_captcha='+captchaField.val(),
			success: function(msg){
				if(msg==1){
					formName.submit();
					//alert('Thank you for your submission');
				}
				else if(msg==0){
					alert('Sorry, the code you entered was invalid. Try Again');
					
					//reset the field and focus on captcha:
					captchaField.parent().find('img').attr('src', pluginPath+'/wp-esa-contest/securimage/securimage_show.php?sid='+Math.random());
					captchaField.val('');
					captchaField.focus();
				}
		   }
		});
		return false; //js submit;
	}
	else{
		//check empty form (If no field is entered):
		err = true; // initially set
		var fields = $j("form#"+id).serializeArray();
		$j(fields).each(function(i, field){
			if( $j("form#"+id+" input[name='"+field.name+"']").attr('type') != 'hidden' && (field.value!=0 && field.value!='') )
				err = false; //alert(field.name+'='+field.value+' & '+err);
		});
		if(err){
			alert('Please fill up at least any one field.');
			return false;
		}
		
		//special/additional check for registration:
		if(id=='register_form'){
			/*if( $j("form#"+id+" select#cons_birth_date_YEAR").val() != $j("form#"+id+" input#c1650_1860_2_2261").val() ){
				$j("form#"+id+" input#c1650_1860_2_2261").addClass('mandatoryErr');
				alert('What year were you born? Insert same as above.');
				return false;
			}*/
			
			//check age:
			if($j('#cons_birth_date_DAY, #cons_birth_date_MONTH, #cons_birth_date_YEAR').length == 3){
				var d=$j('#cons_birth_date_DAY').val()+'/'+$j('#cons_birth_date_MONTH').val()+'/'+$j('#cons_birth_date_YEAR').val();
				if(getAge(d) < 13){
					alert("You Must be 13 years of age to register to the site.");
					return false;
				}
			}
			
			//check agreed:
			if(agreed.length > 0){
				if( ! agreed.attr('checked') ){
					alert('You should agree to the community standards.');
					return false;
				}
			}
		}
		
		//check special:
		if(specialID=='preview-e-card')
			return makePopup(id);
		else
			return true; //form submit, as the form is valid, let it be submitted;
	}
}


