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 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 getFlashMovieObject(movieName)
{
	if (document.embeds && document.embeds[movieName])
		return document.embeds[movieName];
	if (window.document[movieName])
		return window.document[movieName];
	if (navigator.appName.indexOf("Microsoft Internet")==1)
		return document.getElementById(movieName);
}



function getHTTPObject()
{
	try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {}
	try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {}
	try { return new XMLHttpRequest(); } catch(e) {}
	alert("XMLHttpRequest not supported");
	return null;
 }

function LoadHTML(url)
{

	var xmlHttp = getHTTPObject();
	xmlHttp.open("GET",url, false);
	xmlHttp.onreadystatechange = function()
	{
		   if (xmlHttp.readyState != 4)  { return; }
		   var serverResponse = xmlHttp.responseText;

	}
	xmlHttp.send(null);
	return xmlHttp.responseText;
}
function LoadXML(url)
{
	var xmlHttp = getHTTPObject();
	xmlHttp.open("GET",url, false);
	xmlHttp.onreadystatechange = function()
	{
		   if (xmlHttp.readyState != 4)  { return; }
		   var serverResponse = xmlHttp.responseText;
	};
	xmlHttp.send(null);
	return xmlHttp.responseXML.documentElement;
}

function PostXML(url,params)
{
	xmlHttp = false;
	// branch for native XMLHttpRequest object
	if(window.XMLHttpRequest && !(window.ActiveXObject))
	{
		try {
			xmlHttp = new XMLHttpRequest();
		} catch(e) {
			xmlHttp = false;
		}
		// branch for IE/Windows ActiveX version
	} else if(window.ActiveXObject)
	{
		try {
			xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch(e) {
			try {
				xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch(e) {
				xmlHttp = false;
			}
		}
	}

	if (xmlHttp)
	{
		xmlHttp.open( "POST", url, false );
		xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
		xmlHttp.setRequestHeader("Content-length", params.length);
		xmlHttp.setRequestHeader("Connection", "close");
		xmlHttp.send(params);
		return xmlHttp.responseXML.documentElement;
	}
}

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 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 (!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";
		}
	}
}

function submitOrder_1(f)
{
	// disable submit button and change its class
	submitButton = document.getElementById("submitForm");
	submitButton.className = "submit_disable";
	submitButton.disabled = true;

	ReqFields = new Array("cut_pages");
	for (i=0;i<ReqFields.length; i++)
	{
		fieldName = ReqFields[i];
		if (trim(f[fieldName].value) == "")
		{
			cMessage = eval("_"+fieldName);
			alert(cMessage);
			releaseSubmitDisabled(submitButton);
			f[fieldName].focus();
			return false;
		}
	}

	releaseSubmitDisabled(submitButton);
	return true;
}

function releaseSubmitDisabled(submitButton, submitClass)
{
	if (submitClass == null || submitClass == undefined) submitClass = "submit_1";
	submitButton.className = submitClass;
	submitButton.disabled = false;
}

var _priceLoader = null;
var _cPrice = 0;
 function calOrder(f){
 	// basic prices
 	clearTimeout(_priceLoader);
	var _landingPage = 399;
	var _firstPage = 649;
	var _innerPage = 249;
 	var _dynamicMenu = 49;

	// prices percent variation
	var _percentResolution = 15;
	var _percentTime = new Array(0, 15, 40);
	var _percentMirror = 50;

	var _totalPrice = 0;
	priceContainer = document.getElementById("price_screen");

	if (f.cut_pages.value == "" && _cPrice > 0)
	{
		_cPrice = 0;
		priceContainer.innerHTML = "<img src=\""+_img_loading+"\" alt=\"\" class=\"price_loader\" />";
		_priceLoader = setTimeout("showPrice('"+_totalPrice+"')", 500);
		return;
	}
	else if (f.cut_pages.value == "") return;

	var _numPages = parseFloat(f.cut_pages.value) - 1;
	if (f.cut_pages.value == 0) {
		_totalPrice = _landingPage;
	}
	else {
		_totalPrice = _firstPage + (_numPages * _innerPage);
	}
	if (f.cut_resolution.value == "2") _totalPrice += Math.round(_totalPrice * (_percentResolution/100));
	if (parseFloat(f.cut_dmenu.value) > 0) _totalPrice += (parseFloat(f.cut_dmenu.value)*_dynamicMenu);
	if (f.cut_mirror.checked == true) _totalPrice += Math.round(_totalPrice * (_percentMirror/100));
	if (f.cut_time.value != "") _totalPrice += Math.round(_totalPrice * (_percentTime[f.cut_time.value]/100));

	_cPrice = _totalPrice;

	priceContainer.innerHTML = "<img src=\""+_img_loading+"\" alt=\"\" class=\"price_loader\"/>";
	_priceLoader = setTimeout("showPrice('"+_totalPrice+"')", 500);
 }

 function showPrice(price)
 {
 	priceContainer = document.getElementById("price_screen");
 	priceContainer.innerHTML = "<span class=\"price\">"+price+"</span> "+_currency;
 }

 function initUploadObj()
 {
	swfu = new SWFUpload({
			flash_url : _base+"/images/swfupload.swf",
			upload_url : _base+"/upload.php",
			file_post_name: "order_upload",

			post_params: {"PHPSESSID" : "<?php echo session_id(); ?>"},

			file_size_limit : "15 MB",
			file_types : "*.ai;*.psd;*.zip;*.rar;*.fh9;*.fh8;*.fh10;*.fh11;*.jpg;*.png;*.gif;*.bmp;",
			file_types_description : "PSD, AI, JPG, FH, ZIP, RAR",
			file_upload_limit : 100,
			file_queue_limit : 0,
			debug: false,

			// Button settings
			button_image_url: _base+"/images/folder_button.gif",
			button_width: "22",
			button_height: "20",
			button_placeholder_id: "folder",

			custom_settings : {
				progress_target : "fsUploadProgress",
				upload_successful : false
			},

			// Event handler settings
			swfupload_loaded_handler : swfUploadLoaded,

			file_dialog_start_handler: fileDialogStart,
			file_queued_handler : fileQueued,
			file_queue_error_handler : fileQueueError,
			file_dialog_complete_handler : fileDialogComplete,

			//upload_start_handler : uploadStart,	// I could do some client/JavaScript validation here, but I don't need to.
			upload_progress_handler : uploadProgress,
			upload_error_handler : uploadError,
			upload_success_handler : uploadSuccess,
			upload_complete_handler : uploadComplete
		});
 }

 function submitOrder_2()
{
	// the submit function is called from within handlers.js file for SWFUpload() !
	// disable submit button and change its class
	f = document.getElementById("order_form");

	submitButton = document.getElementById("submitForm");
	submitButton.className = "submit_disable";
	submitButton.disabled = true;

	ReqFields = new Array("order_fName","order_lName","order_phone","order_email", "txtFileName", "contact_security");
	for (i=0;i<ReqFields.length; i++)
	{
		fieldName = ReqFields[i];
		if (trim(f[fieldName].value) == "")
		{
			cMessage = eval("_"+fieldName);
			alert(cMessage);
			releaseSubmitDisabled(submitButton);
			f[fieldName].focus();
			return false;
		}

		if ((fieldName == "order_phone" && !checkPhone(f[fieldName].value)) || (fieldName == "order_email" && !checkEmail(f[fieldName].value)))
		{
			cMessage = eval("_"+fieldName+"_invalid");
			alert(cMessage);
			releaseSubmitDisabled(submitButton);
			f[fieldName].focus();
			return false;
		}

		if (fieldName == "contact_security")
		{
			var url = _base+"/cutit_ajax.php?action=get_session&session_name=security_code";
			var security_code = LoadHTML(url);
			if(security_code != null && trim(f[fieldName].value) != security_code)
			{
				alert(_contact_security);
				releaseSubmitDisabled(submitButton, "submit_2");
				f[fieldName].focus();
				return false;
			}
		}
	}

	return true;
}

function show_site(site_id)
{
	popupWin(_base+"/example_popup.php?id="+site_id, 1000, 643);
}

function view_source (type, source, tab)
{
	frame = document.getElementById("example_window");
	if (source == frame.src) return;

	frame.src = (type == "PREVIEW") ? source : "example_source.php?type="+type+"&src="+source;

	tab = tab.parentNode;
	tab.className = "selected";
	tabs = tab.parentNode;
	for (i=0; i < tabs.childNodes.length; i++)
	{
		if (tabs.childNodes[i].nodeType != 1) continue;
		if (tabs.childNodes[i] != tab) tabs.childNodes[i].className = "";
	}
}

function reloadCaptcha()
{
	var captcha = document.getElementById("captcha_image");
	captcha.innerHTML = "<img src=\""+_base+"/CaptchaSecurityImages.php\" />";
}

function submitContact(f)
{
	// disable submit button and change its class
	submitButton = document.getElementById("submitForm");
	submitButton.className = "submit_2_disable";
	submitButton.disabled = true;

	ReqFields = new Array("contact_fName","contact_phone","contact_email","contact_security");
	for (i=0;i<ReqFields.length; i++)
	{
		fieldName = ReqFields[i];
		if (trim(f[fieldName].value) == "")
		{
			cMessage = eval("_"+fieldName);
			alert(cMessage);
			releaseSubmitDisabled(submitButton, "submit_2");
			f[fieldName].focus();
			return false;
		}

		if (fieldName == "contact_email" && !checkEmail(f[fieldName].value))
		{
			alert(_contact_emailInvalid);
			releaseSubmitDisabled(submitButton, "submit_2");
			f[fieldName].focus();
			return false;
		}

		if (fieldName == "contact_phone" && !checkPhone(f[fieldName].value))
		{
			alert(_contact_phoneInvalid);
			releaseSubmitDisabled(submitButton, "submit_2");
			f[fieldName].focus();
			return false;
		}

		if (fieldName == "contact_security")
		{
			var url = _base+"/cutit_ajax.php?action=get_session&session_name=security_code";
			var security_code = LoadHTML(url);
			if(security_code != null && trim(f[fieldName].value) != security_code)
			{
				alert(_contact_security);
				releaseSubmitDisabled(submitButton, "submit_2");
				f[fieldName].focus();
				return false;
			}
		}
	}

	if (f.contact_resume && f.contact_resume.value !="")
	{
		// check and restrict upload file extension
		extension = getFileExtension(f.contact_resume.value);
		var pattern = /^\.(doc|pdf|txt)/i;
		if (!extension.match(pattern))
		{
			alert (_contact_fileType);
			releaseSubmitDisabled(submitButton, "submit_2");
			return false;
		}
	}

	if (f.contact_resume && f.contact_resume.value !="")
	{
		f.target = "postFrame";
		postFrame = document.getElementById("postFrame");
		postFrame.onload = uploadDone;
		return true;
	}
	else
	{
		advAJAX.submit(f, {
		    onSuccess : function(obj) {
		    		if (obj.responseText == "success")
		    		{
		    			alert (_contact_success);
		    			f.reset();
		    			reloadCaptcha();
		    			releaseSubmitDisabled(submitButton, "submit_2");
		    		}
		    		else
		    		{
		    			alert (_contact_fail);
		    			releaseSubmitDisabled(submitButton, "submit_2");
		    		}
		    }
		});
	}
	return false;

	releaseSubmitDisabled(submitButton, "submit_2");
	return false;
}

function uploadDone() { //Function will be called when iframe is loaded
	var postFrame = (document.getElementById("postFrame").contentDocument ) ? document.getElementById("postFrame").contentDocument : document.getElementById("postFrame").contentWindow.document;
	var ret = postFrame.getElementsByTagName("body")[0].innerHTML;
	f = document.getElementById("jobsContactForm");
	submitButton = document.getElementById("submitForm");

	if(ret == "success") {
		alert (_contact_success);
		f.reset();
		releaseSubmitDisabled(submitButton, "submit_2");
	}
	else
	{
		alert (_contact_fail);
		releaseSubmitDisabled(submitButton, "submit_2");
	}
}

function unsubscribe(f)
{
	if (confirm(_unsubscribe))
	{
		advAJAX.submit(f, {
		    onSuccess : function(obj) {
		    		alert (obj.responseText);
		    }
		});
	}
	return false;
}
