function checkEmail(str) {
///// function for validating email address
		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
		} else if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		    return false
		} else 	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		    return false
		} else  if (str.indexOf(at,(lat+1))!=-1){
		    return false
		} else 	 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		   return false
		} else  if (str.indexOf(dot,(lat+2))==-1){
		    return false
		} else if (str.indexOf(" ")!=-1){
		     return false
		} else {
 		 	return true
 		}
}

function addLoadEvent(func)
{
	var oldonload = window.onload;
	if (typeof window.onload != 'function')
		window.onload = func;
	else
	{
		window.onload = function()
		{
			if (oldonload) oldonload();
			func();
		}
	}
}

function Set_Cookie( name, value, expires, path, domain, secure )
{
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );

	/*
	if the expires variable is set, make the correct
	expires time, the current script below will set
	it for x number of days, to make it for hours,
	delete * 24, for minutes, delete * 60 * 24
	*/
	if ( expires )
	{
	expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );

	document.cookie = name + "=" +escape( value ) +
	( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
	( ( path ) ? ";path=" + path : "" ) +
	( ( domain ) ? ";domain=" + domain : "" ) +
	( ( secure ) ? ";secure" : "" );
}

// this deletes the cookie when called
function Delete_Cookie( name, path, domain )
{
	if ( Get_Cookie( name ) ) document.cookie = name + "=" +
	( ( path ) ? ";path=" + path : "") +
	( ( domain ) ? ";domain=" + domain : "" ) +
	";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

// this function gets the cookie, if it exists
function Get_Cookie( name )
{
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) &&
	( name != document.cookie.substring( 0, name.length ) ) )
	{
	return null;
	}
	if ( start == -1 ) return null;
	var end = document.cookie.indexOf( ";", len );
	if ( end == -1 ) end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );
}
function checkPhone(str)
{
	rePhoneNumber = new RegExp(/^[0-9]{0,3}\s?\-?\s?[0-9]{7,10}$/);
	if (!rePhoneNumber.test(str))
		return false;

	return true;

}

function IsNumeric(sText)
{
   var ValidChars = "0123456789.-, ";
   var IsNumber=true;
   var Char;


   for (i = 0; i < sText.length && IsNumber == true; i++)
      {
      Char = sText.charAt(i);
      if (ValidChars.indexOf(Char) == -1)
         {
         IsNumber = false;
         }
      }
   return IsNumber;
 }

function trim(strText) {
/// TRIM STRING FUNCTION
    // this will get rid of leading spaces
    while (strText.substring(0,1) == ' ')
        strText = strText.substring(1, strText.length);
    // this will get rid of trailing spaces
    while (strText.substring(strText.length-1,strText.length) == ' ')
        strText = strText.substring(0, strText.length-1);
   return strText;
}

function escapeString(sString)
{
// DETECT WHAT TO PUT STRING IN FOR HTML FORM ( ' OR " ) DEPANDING ON STRING CONTENTS
	if (sString.indexOf("'") == -1)
		valSep = "'";
	else
		valSep = '"';
	return valSep+sString+valSep;
}

function replaceSubstring(inputString, fromString, toString) {
 // GOES THROUGH THE INPUTSTRING AND REPLACES EVERY OCCURRENCE OF FROMSTRING WITH TOSTRING
   var temp = inputString;
   if (fromString == "") {
      return inputString;
   }
   if (toString.indexOf(fromString) == -1) { // If the string being replaced is not a part of the replacement string (normal situation)
      while (temp.indexOf(fromString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(fromString));
         var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
         temp = toTheLeft + toString + toTheRight;
      }
   } else { // String being replaced is part of replacement string (like "+" being replaced with "++") - prevent an infinite loop
      var midStrings = new Array("~", "`", "_", "^", "#");
      var midStringLen = 1;
      var midString = "";
      // Find a string that doesn't exist in the inputString to be used
      // as an "inbetween" string
      while (midString == "") {
         for (var i=0; i < midStrings.length; i++) {
            var tempMidString = "";
            for (var j=0; j < midStringLen; j++) {tempMidString += midStrings[i];}
            if (fromString.indexOf(tempMidString) == -1) {
               midString = tempMidString;
               i = midStrings.length + 1;
            }
         }
      } // Keep on going until we build an "inbetween" string that doesn't exist
      // Now go through and do two replaces - first, replace the "fromString" with the "inbetween" string
      while (temp.indexOf(fromString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(fromString));
         var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
         temp = toTheLeft + midString + toTheRight;
      }
      // Next, replace the "inbetween" string with the "toString"
      while (temp.indexOf(midString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(midString));
         var toTheRight = temp.substring(temp.indexOf(midString)+midString.length, temp.length);
         temp = toTheLeft + toString + toTheRight;
      }
   } // Ends the check to see if the string being replaced is part of the replacement string or not
   return temp; // Send the updated string back to the user
}

function popupWin(popUrl, width, height)
{
	if (!navigator.appName.indexOf("Microsoft")) width+=20;
	height+=5;
	topVar=((screen.height / 2)-(height/2));
	leftVar=((screen.width / 2)-(width/2));
	window.open(popUrl, "PopUp", "height="+height+", width="+width+", top="+topVar+", left="+leftVar+", scrollbars=yes, status=no, location=no, resize=yes, menubar=no, titlebar=no, toolbar=no");
}

function getFileExtension(filename)
{
	if( filename.length == 0 ) return "";
	var dot = filename.lastIndexOf(".");
	if( dot == -1 ) return "";
	var extension = filename.substr(dot,filename.length);
	return extension
}

function fix_external_links() {
	if (!document.getElementsByTagName) return;
	var anchors = document.getElementsByTagName("a");

	var basicPattern = new RegExp('^(http:\/\/|https:\/\/)');
	var pattern = new RegExp('^(http:\/\/|https:\/\/)'+location.hostname);

	for (var i = 0; i < anchors.length; i++)
	{
		var anchor = anchors[i];
		if (anchor.getAttribute("rel") && anchor.getAttribute("rel") == "external") {
			anchor.target = "_blank";
		}
		else if (getFileExtension(anchor.href) == ".pdf") {
			anchor.target = "_blank";
		}
		else if (!anchor.href.match(basicPattern))  // this is for links such as "javascript" or "#" which do not include http or https at all !!
			continue;
		else if (!anchor.href.match(pattern) && !anchor.getAttribute("rel") || (anchor.getAttribute("rel") && anchor.getAttribute("rel") != "ibox")) {
			anchor.target = "_blank";
		}
	}
}

$(document).ready(function() {
	
	$(".mainContact").parents().find(".short-contact").closest(".layoutrow").remove(); // remove short contact if found on same page as main contact
//	if( $("form#contact").length > 1 ) {
//		$("body").find(".short-contact").closest(".layoutrow").remove(); // remove short contact if found on same page as main contact
//	}
	
	// contact submit handle
	$("form#contact").submit(function()
	{
		// disable submit button and change its class
		$(this).find('input[type="submit"]').addClass("disabled").attr('disabled', true);

		var ReqFields = new Array("contact_fullName", "contact_fName","contact_lName","contact_phone","contact_email");
		for (i=0;i<ReqFields.length; i++)
		{
			fieldName = ReqFields[i];
			cField = $(this).find('input[name="' + fieldName + '"]');
			if (!cField.length) continue;
			
			if (cField.val() == "")
			{
				cTitle = cField.parent().prev().text();
				alert(_please_enter+ " "+cTitle);
				cField.addClass("required").focus();
				$(this).find('input[type="submit"]').removeClass("disabled").removeAttr('disabled');
				return false;
			}
			
			if ((fieldName == "contact_email" && !checkEmail(cField.val())) || (fieldName == "contact_phone" && !checkPhone(cField.val()) ) )
			{
				cTitle = cField.parent().prev().text();
				alert(cTitle + " "+ _invalid);
				cField.addClass("required").focus();
				$(this).find('input[type="submit"]').removeClass("disabled").removeAttr('disabled');
				return false;	
			}
			
			cField.removeClass("required");
		}
		
		if( $("input[name=security_code]").length > 0 ) 
		{
			var input_security = $("input[name=security_code]");
			var input_security_val = trim( $("input[name=security_code]").val() );
			if (trim( input_security_val ) == "")
			{
				alert("Please enter security code");
				$(input_security).focus();
				$(this).find('input[type="submit"]').removeClass("disabled").removeAttr('disabled');
				return false;
			}
	
			$.ajax({
			type: "POST",
			async:false,
			url: _base+"/vp_ajax.php?action=get_session&session_name=security_code",
			data: "action=get_session&session_name=security_code",
			success: function(msg){
					security_code = msg;
				} 
			});
			
			if ( input_security_val != security_code )
			{
				alert("wrong security code");
				$(input_security).focus();
				$(this).find('input[type="submit"]').removeClass("disabled").removeAttr('disabled');
				return false;
			}
			
		}
	
		if (confirm(_contact_confirm))
		{
			action = $(this).attr("action");
			
			$.post(action, $(this).serialize(), function(responseText) {
				f = $("form#contact");
				if (responseText == "success")
		    		{
		    			alert (_contact_success);
		    			$(f).find("input[type=text], input[type=checkbox]").val("").removeAttr("checked");
					$(f).find("textarea").val("");
					$(f).find('input[type="submit"]').removeClass("disabled").removeAttr('disabled');
					render_googleConversionCode();
		    		}
		    		else
		    		{
		    			alert (_contact_fail);
		    			$(f).find('input[type="submit"]').removeClass("disabled").removeAttr('disabled');
		    		}
			});
		}

		return false;	
	});
	
	// login submit handle
	$("form#login").submit(function()
	{
		// disable submit button and change its class
		$(this).find('input[type="submit"]').addClass("disabled").attr('disabled', true);
	
		var ReqFields = new Array("login_email","login_userName", "login_password");
		for (i=0;i<ReqFields.length; i++)
		{
			fieldName = ReqFields[i];
			cField = $(this).find('input[name="' + fieldName + '"]');
			if (!cField.length) continue;
			
			if (cField.val() == "")
			{
				cTitle = cField.parent().prev().text();
				alert(_please_enter+ " "+cTitle);
				cField.addClass("required").focus();
				$(this).find('input[type="submit"]').removeClass("disabled").removeAttr('disabled');
				return false;				
			}
			
			if ( fieldName == "login_email" && !checkEmail( cField.val() ) )
			{
				cTitle = cField.parent().prev().text();
				alert(cTitle + " "+ _invalid);
				cField.addClass("required").focus();
				$(this).find('input[type="submit"]').removeClass("disabled").removeAttr('disabled');
				return false;	
			}
			
			cField.removeClass("required");
		}
		
		action = $(this).attr("action");
			
		$.post(action, $(this).serialize(), function(responseText) {
			f = $("form#login");
			if (responseText == "success")
	    		{
	    			//alert (_login_success);
	    			$(f).find("input[type=text],input[type=password], input[type=checkbox]").val("").removeAttr("checked");
				$(f).find("textarea").val("");
				$(f).find('input[type="submit"]').removeClass("disabled").removeAttr('disabled');
				//window.location.reload();
				
				get_logged_member();
				if( $(".inner_contents_wrap").length && cur_page_id > 0 ) {
					get_page_contents();
				}
				
	    		}
	    		else
	    		{
	    			alert (responseText);
	    			$(f).find('input[type="submit"]').removeClass("disabled").removeAttr('disabled');
	    		}
		});

		return false;	
	});
	
	// show forgot passwod form
	$("#forgot_pass_link,#rem_pass_link").click(function(event){
		event.preventDefault();
		$(".login-box, #forgot_password_wrap").slideToggle();
		//return false;
	});
//	$("#rem_pass_link").click(function(event){
//		event.preventDefault();
//		$("#forgot_password_wrap, .login-box").slideToggle();
//		//return false;
//	});
	$("#show_login_box").click(function(event){
		event.preventDefault();
		$(".short_login_wrap").slideToggle();
		//return false;
	});
	
	// forgot password submit handle
	$("form#forgot_password").submit(function()
	{
		// disable submit button and change its class
		$(this).find('input[type="submit"]').addClass("disabled").attr('disabled', true);
	
		var ReqFields = new Array("reminderEmail");
		for (i=0;i<ReqFields.length; i++)
		{
			fieldName = ReqFields[i];
			cField = $(this).find('input[name="' + fieldName + '"]');
			if (!cField.length) continue;
			
			if (cField.val() == "")
			{
				cTitle = cField.parent().prev().text();
				alert(_please_enter+ " "+cTitle);
				cField.addClass("required").focus();
				$(this).find('input[type="submit"]').removeClass("disabled").removeAttr('disabled');
				return false;				
			}
			
			if ( fieldName == "reminderEmail" && !checkEmail( cField.val() ) )
			{
				cTitle = cField.parent().prev().text();
				alert(cTitle + " "+ _invalid);
				cField.addClass("required").focus();
				$(this).find('input[type="submit"]').removeClass("disabled").removeAttr('disabled');
				return false;	
			}
			
			cField.removeClass("required");
		}
		
		action = $(this).attr("action");
			
		$.post(action, $(this).serialize(), function(responseText) {
			f = $("form#forgot_password");
			if (responseText == "success")
	    		{
	    			alert (_forgot_success);
	    			$(f).find("input[type=text],input[type=password], input[type=checkbox]").val("").removeAttr("checked");
				$(f).find("textarea").val("");
				$(f).find('input[type="submit"]').removeClass("disabled").removeAttr('disabled');
	    		}
	    		else
	    		{
	    			alert (responseText);
	    			$(f).find('input[type="submit"]').removeClass("disabled").removeAttr('disabled');
	    		}
		});

		return false;	
	});
	
});

function get_logged_member()
{
	$(".login_box").fadeOut("fast",function(){
		action = _base + "/vp_ajax.php?action=get_logged_member";
		$.post(action, "", function(responseText) {
			if( responseText != "" ) {
				$(".login_box").html(responseText);				
			}
			$(".login_box").fadeIn("slow");
		});
	});
}

function get_page_contents()
{
	if( $(".inner_contents_wrap").length && cur_page_id > 0 )
	{
		action = _base + "/vp_ajax.php?action=get_page_contents";
		$.post(action, { id:cur_page_id }, function(responseText) {
			$(".inner_contents_wrap").html(responseText);
		});
	}
	
}

function isPhoneNumber(str) {
    if (!str.match(/^\+?(\-?[0-9]+)+$/)) {
        return false;
    }
    
    return true;
}

// Function for showing and positioning / hiding side banner
$(function(){
	var $hideme = $('.skyscraper'); //Change the CSS ID selector to whatever you want to check
	hidden_class = 'hidden'; 
	window_min_width = $(".container").width()+20; // minimum screen width required to show the banner (without the width of the banner itself)
	banner_width = 120;
	position_top = 20;
	
	$hideme.css('display','none').addClass(hidden_class);
	width_to_hide = window_min_width + (banner_width*2);
	
	$(window).scroll(function(){
		$hideme.css("position", "fixed");
		if  ($(window).scrollTop() > position_top){
			$hideme.css('top',0);
		}
		if  ($(window).scrollTop() <=  position_top){
			$hideme.css('top',position_top-$(window).scrollTop());
		}
	}); 
	
	$(window).resize(function(){//When the browser resizes
		if($(this).width() < width_to_hide){ //If the browser width is LESS THAN 900px
			$hideme.css('display','none').addClass(hidden_class); //Makes the ad banner display none
		}
		//If the window is equal or MORE THAN 900px AND has a class "hidden":
		if($(this).width() >= width_to_hide){
			position_left = ($(this).width() - window_min_width)/2 - banner_width;
			position_right = ($(this).width() - window_min_width)/2 + window_min_width;

			$hideme.each(function(){
				if ($(this).hasClass("skyscraper_right")) {
					$(this).css('left',position_right);
				} else {
					$(this).css('left',position_left);
				}
			});

			if ($hideme.hasClass(hidden_class)) {
				$hideme.fadeIn(500).addClass(hidden_class); //fade back in.
			}
			
		}
	})
});
$(window).load(function(){$(window).scroll().resize();}); //On a COMPLETE page load fake a resize to run above function

// function for resolving drop menu issues on iphone / ipad
$(document).ready(function() {
	if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/iPad/i))) {				
		$(".container").bind("click", function(e) {});
	}
});

function randomFromTo(from, to) {
       return Math.floor(Math.random() * (to - from + 1) + from);
}

function reloadCaptcha(elem_id)
{
	if (elem_id == null) elem_id = "captcha_image";
	var new_width = randomFromTo(65,70);
	var new_height = randomFromTo(20,25);
	$("#"+elem_id).html("<img src=\""+_base+"/CaptchaSecurityImages.php?width="+new_width+"&height="+new_height+"&characters=5&cScheme=blue\" alt=\"\">");
}
/*$(function(){
	$("[title]").tooltip({offset: [25,0], effect: 'slide'}).dynamic({ bottom: { direction: 'down',bounce: true }});
})*/

//function positionFooter(){
//	if($(document.body).height() <= $(window).height()){
//		$("#footer_container").show();
//		var footerHeight = $("#footer_container").height()+parseInt($("#footer_container").css('paddingTop'))+parseInt($("#footer_container").css('paddingBottom'))+parseInt($("#footer_container").css('marginTop'))+parseInt($("#footer_container").css('marginBottom'));
//		$("#footer_container").css({position: "absolute",left: "0px", top:($(document).height()-footerHeight)+"px",width:"100%"})
//	}
//}

function positionFooter(){
	if($(document.body).height() <= $(window).height()){
		var footerHeight = $(".footer").height()+parseInt($(".footer").css('paddingTop'))+parseInt($(".footer").css('paddingBottom'))+parseInt($(".footer").css('marginTop'))+parseInt($(".footer").css('marginBottom'));
		var headerHeight = $(".header").height()+parseInt($(".header").css('paddingTop'))+parseInt($(".header").css('paddingBottom'))+parseInt($(".header").css('marginTop'))+parseInt($(".header").css('marginBottom'));
		var containerHeight = parseInt($(window).height()) - footerHeight -headerHeight;
		$(".page_inner").css("min-height",containerHeight+"px");
	}
}

function render_googleConversionCode() {
//	var's google_conversion_id && google_conversion_label defined in headerHead
	if( google_conversion_id > 0 && google_conversion_label.length > 0 ) {
		var imgConversionSrc = "http://www.googleadservices.com/pagead/conversion/"+google_conversion_id+"/?label="+google_conversion_label+"&amp;guid=ON&amp;script=0";
		var fullConversionCode = '<div style="display:inline;"><img height="1" width="1" style="border-style:none;" alt=""  src="'+imgConversionSrc+'"/></div>';
		$("body").append(fullConversionCode);
	}
}

