// Globals
var mainNavTabsOff, mainNavTabsOn, templateArray, mode_id, project_id, a_bg, a_body, ratingStars;


//########################################################################
//				COMMON EVENT FIRINGS
addEvent(window,'load',maintabs,false);
addEvent(window,'load',inputFX,false);
//addEvent(window,'load',loadAds,false);

//########################################################################
function maintabs() {
	mainNavTabsOff = new Array();
	mainNavTabsOn = new Array();
	var img = $('tabline').getElementsByTagName('img');
	for (var i=0; i<img.length ;i++ )
	{
		if (img[i].className.match('tab') == 'tab') {
			var core = (img[i].src.slice(0,img[i].src.length-7));
			mainNavTabsOn[i] = document.createElement('img');
			mainNavTabsOn[i].setAttribute('src',core+'_hv.jpg');
			mainNavTabsOff[i] = document.createElement('img');
			mainNavTabsOff[i].setAttribute('src',core+'_nm.jpg');
			img[i].onmouseover = (function(i) {return function() {this.src = mainNavTabsOn[i].src}})(i);
			img[i].onmouseout = (function(i) {return function() {(!this.className.match("active")) ? this.src = mainNavTabsOff[i].src : this.src = this.src}})(i);
		}
	}
}

function inputFX(obj) {
	inputSwapBg ('member_signin');
	inputSwapBg('search_scenes');
}

function inputSwapBg(inputCluster) {
	if ($(inputCluster)){
		var fields = $(inputCluster).getElementsByTagName('input');
		for (var i=0; i<fields.length; i++ ){
			if(fields[i].getAttribute("value") != "Login" && fields[i].getAttribute("value") != "Logout"){ // do not aply to button inputs
				 // set effect immediately on load
				if (fields[i].value != fields[i].getAttribute("title") && fields[i].value != "") {
					fields[i].className = "focusedField";
					fields[i].value = fields[i].value;
				} else {
					fields[i].value = fields[i].getAttribute("title");
				}
				// on focus, blur, mousedown behaviour
				fields[i].onfocus = function() {
					if (this.value == this.getAttribute("title")) {
						this.className = "focusedField";
						this.value = "";
					}
				};
				fields[i].onblur = function() {
					if (this.value == "") {
						this.className = "genericField";
						this.value = this.getAttribute("title");
					}
				};
				fields[i].onmousedown = function() {
					if (this.value == this.getAttribute("title")) {
						this.className = "focusedField";
						this.value = "";
					}
				};
			}
		}
	}
}

function loadAds() {
	if ($("footer_advertising_iframe")) {
		$("footer_advertising_iframe").src = "includes/footer_sponsored_links.html";
	}
	if ($("banner_advertising_iframe")) {
		$("banner_advertising_iframe").src = "includes/header_sponsored_links.html";
	}
}

function alertObject(functions,title, message) {

	// containers
	a_bg = document.createElement('div');
	a_body = document.createElement('div');
	var a_content = document.createElement('div');
	var a_title = document.createElement('h1');
	var a_titleText = document.createTextNode(title);
	var a_message = document.createElement('p');
	var commands = document.createElement('div');

	a_content.className = "a_contentContainer";
	// test for IE 6 for PNG transparency
	var browser = new detectBrowser();
	a_body.className =	(browser.ie6 && !browser.ie7) ? 'a_bodyBG ie6_png ie6_fixed' : 'a_bodyBG png fixed';
	a_bg.className =	(browser.ie6 && !browser.ie7) ? 'a_fadeBG ie6_fixed' : 'a_fadeBG fixed';

	a_title.appendChild(a_titleText);
	a_content.appendChild(a_title);
	a_message.innerHTML = message;
	a_content.appendChild(a_message);

	//buttons
	var yes, no, cancel, img, text;
	yes = document.createElement('a');
	img = document.createElement('img');
	text = document.createTextNode(functions["yes"][1]);
	img.setAttribute('src','images/button_medium_cap_grey.gif');
	yes.appendChild(img);
	yes.appendChild(text);
	yes.className = 'mediumGrey mediumButton';
	yes.setAttribute('href','#');
	yes.onclick = function () {eval(functions["yes"][0]); return false;};

	no = document.createElement('a');
	img = document.createElement('img');
	text = document.createTextNode(functions["no"][1]);
	img.setAttribute('src','images/button_medium_cap_grey.gif');
	no.appendChild(img);
	no.appendChild(text);
	no.className = 'mediumGrey mediumButton';
	no.setAttribute('href','#');
	no.onclick = function () {eval(functions["no"][0]); return false;};

	cancel = document.createElement('a');
	img = document.createElement('img');
	text = document.createTextNode(functions["cancel"][1]);
	img.setAttribute('src','images/button_medium_cap_grey.gif');
	cancel.appendChild(img);
	cancel.appendChild(text);
	cancel.className = 'mediumGrey mediumButton';
	cancel.setAttribute('href','#');
	cancel.onclick = function () {eval(functions["cancel"][0]); return false;};

	//draw alert buttons
	(functions["cancel"][0] != null) ? a_content.appendChild(cancel) : null;
	(functions["no"][0]		!= null) ? a_content.appendChild(no) : null;
	(functions["yes"][0]	!= null) ? a_content.appendChild(yes) : null;

	a_body.appendChild(a_content);
	document.body.appendChild(a_bg);
	document.body.appendChild(a_body);

	// IE doesnt support positioned:fixed CSS - assign it via JS
	if (browser.ie6 && !browser.ie7) {
		var bgPos = centerOnScreen(0,0);
		a_bg.style.top = bgPos.yPadding;

		var bodyPos = centerOnScreen(250,100);
		a_body.style.left = bodyPos.xCenter;
		a_body.style.top = bodyPos.yCenter;

		window.onscroll = function () {
			var bgPos = centerOnScreen(0,0);
			a_bg.style.top = bgPos.yPadding;

			var bodyPos = centerOnScreen(250,100);
			a_body.style.left = bodyPos.xCenter;
			a_body.style.top = bodyPos.yCenter;

		};
	}
}

function centerOnScreen(x_offset,y_offset) {
	var browser = new detectBrowser();
	var positionData = new Object();

	if (browser.ie6 && !browser.ie7) {
		// IE 6 Only
		positionData.width = document.documentElement.clientWidth;
		positionData.height = document.documentElement.clientHeight;
		positionData.xPadding = document.documentElement.scrollLeft;
		positionData.yPadding = document.documentElement.scrollTop;
	} else {
		// Everything else
		positionData.width = window.innerWidth;
		positionData.height = window.innerHeight;
		positionData.xPadding = window.pageXOffset;
		positionData.yPadding = window.pageYOffset;
	}

	positionData.xCenter = (positionData.width/2) - x_offset + positionData.xPadding;
	positionData.yCenter = (positionData.height/2) - y_offset + positionData.yPadding;

	return positionData;
}


function killAlert() {
	a_body.parentNode.removeChild(a_body);
	a_bg.parentNode.removeChild(a_bg);
	a_body = null;
	a_bg = null;
	window.onscroll = null; // destroy the scroll alert event
}

function cleanEmail(string) {
}


//########################################################################
//				HOMEPAGE SPECIFIC BEHAVIOUR
function scenestabs(tab) {
	var s_tabs = $('scenestabs').getElementsByTagName('a');
	for (var i=0; i<s_tabs.length ;i++ )
	{
		s_tabs[i].onmousedown = (function(i) {return function() {scenestabs(i)}})(i); // bind tabbing event
		// reset tabs
		s_tabs[i].className = "tab";
		s_tabs[i].firstChild.src = "images/homepage/scenetabs_start_off.gif";
		document.getElementById('box_'+i).style.display = "none";
	}
	s_tabs[tab].className = "tab active";
	s_tabs[tab].firstChild.src = "images/homepage/scenetabs_start_on.gif";
	document.getElementById('box_'+tab).style.display = "block";
}

var splashPics = new Array();
function splashscreens() {
	var p_src = ($('splashpic').src.slice(0, $('splashpic').src.length-5));
	var splashLinks = $('numbers').getElementsByTagName('a');
	for (var i=0; i<splashLinks.length; i++ ){
		// create event and make a splash picture to bind to event
		splashLinks[i].onmousedown = (function(i) {return function() {switchSplash(i)}})(i); // bind splash swap
		splashPics[i] = document.createElement('img');
		splashPics[i].src = p_src + i + '.jpg';
	}
	// assign random pic
	var rand = Math.floor(Math.random()*5)
	switchSplash(rand);
}

function switchSplash(pic) {
	$('splashpic').src = splashPics[pic].src;
}


//########################################################################
//				STEP 1 BEHAVIOUR

function detectOS() {
	var agent = navigator.userAgent;
	var os = null;
	os = (agent.match(/Windows NT 6\.0/im)) ? "Vista" : os ;
	os = (agent.match(/Windows NT 5\.1/im)) ? "XP" : os ;
	os = (agent.match(/Mac OS X/)) ? "Mac" : os ;
	return os; // default will return NULL
}

function registrationBlock() {
	var browser = new detectBrowser();
	var platform = detectOS();

	if (platform == "Mac"){
		alertObject({'yes':["sendMacEmail(); killAlert()","Ok"], 'no':[null,null], 'cancel':[null,null]},'Attention',"We are currently working on a Mac version, so please send us your email address so we can notify you when we're done. <br><input id='mac_address' type='text' class='focusedField' />");
	} else if (platform == null){
		alertObject({'yes':["killAlert()","Continue"], 'no':[null,null], 'cancel':[null,null]},'Attention',"Please be aware of the SceneCaster system requirements. We are currently working on versions for non-Windows systems, so please be patient.");
	}
}

//########################################################################
//				MAKE A SCENE BEHVIOUR
function mas_linkBindings() {
	//templateArray = new Array(565,606,556,1000004549,1000004553,1000002058,1000004548,990,570,569,1000004555,578,1000004579,571); // use this array to launch scene project ID
	templateArray = new Array();
	var links = $('template_thumbnail_rollovers').getElementsByTagName('a');
	var sceneId = 0;
	for(i=0; i<links.length; i++){
		templateArray[i] = links[i].getAttribute('scene').substr(6);
		links[i].onclick = (function(i) {return function() {setProjectId(templateArray[i]); $('active').id=""; $('thumbnail').src="../app/projectsnapshots/"+(templateArray[i])+".jpg"; this.id="active"; return false;} })(i);
	}
	$('launchTemplate').onclick	= function() {launchTemplate();return false;};	// template launch process
	$('launchWizard').onclick 	= function() {launchWizard();return false;};		// wizard launch process
	$('launchScratch').onclick 	= function() {launchScratch();return false;};	// scratch launch process
	$('launchScratchThumb').onclick = function() {launchScratch();return false;};	// scratch launch process
}

function setProjectId(id) {
	project_id = id;
}

function launchTemplate() {
	var bAppInstalled = AppInstalled(strReqVersion);
	
	mode_id = 2;
	(project_id == undefined) ?  project_id = templateArray[0] : project_id = project_id;
	var refUrl = "designer/scenecaster_system_check.php?project_id=" + project_id + "&mode_id=" + mode_id + "&scene_type=interior";
	
	if (bAppInstalled) {
		OpenApp(refUrl);
	} else {
		var cookie_date = new Date();  // current date & time
		cookie_date.setTime ( cookie_date.getTime() + (60*60*24*30) );
		document.cookie = "sc_refurl="+document.location.href+"; expires=" + cookie_date.toGMTString();
		location.href = "install.php?refUrl="+encodeURIComponent(refUrl);
	}
}

function launchWizard() {
	
	//alert("starting wizard launch");
	var fields = $('mas_wizard').getElementsByTagName('input');
	var errors = new Array();
	/*===========================*/
	// SANITIZE RULES:
		// fill blank fields with 0, and sanitize non-blank fields
		// 999 ft max
		// no walls less than 1 ft.
		// 99 inches converted to ft. in.
	/*===========================*/
	// rewrite double digit inches for feet
	if ($('length_inches').value >= 12) {
		$('length_feet').value = (trimString($('length_feet').value) == "") ? 0 : $('length_feet').value;
		$('length_feet').value = parseInt($('length_feet').value) + (Math.floor($('length_inches').value/12));
		$('length_inches').value = $('length_inches').value%12;
	}
	if ($('width_inches').value >= 12) {
		$('width_feet').value = (trimString($('width_feet').value) == "") ? 0 : $('width_feet').value;
		$('width_feet').value = parseInt($('width_feet').value) + (Math.floor($('width_inches').value/12));
		$('width_inches').value = $('width_inches').value%12;
	}

	for (i=0; i<fields.length; i++) {
		// test if empty or 0
		if (fields[i].value !="" && fields[i].value != 0) {
			if (!/^\d+$/.test(fields[i].value))	{
				errors.push([fields[i],"contains invalid characters - use only whole numbers"]); // if invalid characters, add to error list
			}
		} else {
			fields[i].value = 0; // fill blank fields with 0
		}
	}

	if ($("length_feet").value <= 11 && $("length_feet").value == 0) {errors.push([$("length_feet"),"must be longer than 1 ft."]);} // if this dimension is less that 1 ft
	if ($("width_feet").value <= 11 && $("width_feet").value == 0) {errors.push([$("width_feet"),"must be longer than 1 ft."]);}// if this dimension is less that 1 ft

	// ERROR PRINTOUT
	($('mas_error')) ? $('container_content').removeChild($('mas_error')) : null; // delete existing error printout


	//alert("checking form for errors...");
	// ERROR array contains list of HTMLelements and their error msg
	if (errors.length > 0) {
		// printout error message block
		var errorsGroup = document.createElement('ol');
		errorsGroup.id = "mas_error";
		errorsGroup.className = "mas_error";

		for (i=0; i<errors.length; i++) {
			errors[i][0].className = errors[i][0].className + " mas_error"; // hilight the errors
			errors[i][0].onmousedown = function () {this.className = "focusedField";}; //removes the "mas_error" class when user clicks field
			var errorMessage = document.createElement('li');
			errorMessage.appendChild(document.createTextNode(errors[i][0].getAttribute('title') + ' ' + errors[i][1])); // print out errors
			errorsGroup.appendChild(errorMessage);
		}
		$('container_content').appendChild(errorsGroup);
	} else {
		for (i=0; i<fields.length; i++) {
			fields[i].className = "focusedField";
		}
		//alert("trying to check app");
		var bAppInstalled = AppInstalled(strReqVersion);
		//alert("app installed? "+bAppInstalled);
        var refUrl = "designer/scenecaster_system_check.php?project_id=0&mode_id=3&scene_type=interior&mLengthFeet="+fields[0].value+"&mLengthInches="+fields[1].value+"&mWidthFeet="+fields[2].value+"&mWidthInches="+fields[3].value+"&mHeightFeet=0&mHeightInches=0&salt="+(Math.random()*100);
        
		if (bAppInstalled) {
			OpenInterior(fields[0].value,fields[1].value,fields[2].value,fields[3].value,"0","0");
		} else {
			var cookie_date = new Date();  // current date & time
			cookie_date.setTime ( cookie_date.getTime() + (60*60*24*30) );
			document.cookie = "sc_refurl="+document.location.href+"; expires=" + cookie_date.toGMTString();
			location.href = "install.php?refUrl="+encodeURIComponent(refUrl);
		}
	}
}

function launchScratch() {
	var bAppInstalled = AppInstalled(strReqVersion);
    var refUrl = "designer/scenecaster_system_check.php?project_id=0&mode_id=0&scene_type=interior";
    
	if (bAppInstalled) {
		OpenApp(refUrl);
	} else {
		var cookie_date = new Date();  // current date & time
		cookie_date.setTime ( cookie_date.getTime() + (60*60*24*30) );
		document.cookie = "sc_refurl="+document.location.href+"; expires=" + cookie_date.toGMTString();
		location.href = "install.php?refUrl="+encodeURIComponent(refUrl);
	}
}

//########################################################################
//				SCENECASTS BEHAVIOURS
//==============================	EIP =======================
var eip_fields = new Array();
var current_focus;

function eipBehaviour (enabled) {

	// collect all EIP elements
	var inputs 	= $('eip').getElementsByTagName('input');
	var textAreas 	= $('eip').getElementsByTagName('textarea');

	for (i=0; i<inputs.length; i++){
		(inputs[i].getAttribute('title') == 'applyEditInPlace') ? eip_fields.push(inputs[i]) : null;
	}
	for (i=0; i<textAreas.length; i++){
		(textAreas[i].getAttribute('title') == 'applyEditInPlace') ? eip_fields.push(textAreas[i]) : null;
	}

	// input fields
	for (i=0; i<eip_fields.length; i++){
		if (enabled == true){
			eip_fields[i].onmouseover = function () {eip_fieldFX(this);}
			eip_fields[i].onmouseout = 	function () {(this != current_focus) ? this.className = '': this.className = 'eip_field_edit';}
			eip_fields[i].onfocus =	 	function () {current_focus = this; eip_fieldFX(this); eip_commandButtons(this);}
			eip_fields[i].onclick =	 	function () {current_focus = this; eip_fieldFX(this); eip_commandButtons(this);}
		} else {
			eip_fields[i].setAttribute('readOnly','true');
		}
	}

	if (enabled == true){
		// drop lists
		$('access').onmouseover = function () {this.className = 'droplist_hover'; droplistItems(this, $('access_list'));}
		$('access').onclick 	= function () {$('access_list').style.display = "block"; eip_fieldFX();}
		$('access').onmouseout 	= function () {this.className = ''; $('access_list').style.display = "none";}

		$('access_list').onmouseover	= function () {$('access_list').style.display = "block"; $('access').className = 'droplist_hover';}
		$('access_list').onclick 		= function () { $('access_list').style.display = "none";}
		$('access_list').onmouseout 	= function () {$('access_list').style.display = "none"; $('access').className = '';}
	}
}

function eip_fieldFX (el) {
	// el is set when focused on textarea or input field
	if (el) {
		for (i=0; i<eip_fields.length; i++){
			(eip_fields[i] != current_focus) ? eip_fields[i].className = '' : eip_fields[i].className = 'eip_field_edit';
		}
		(el == current_focus) ? el.className = 'eip_field_edit' : el.className = 'eip_field_rollover';
	} else {
	// otherwise remove EIP appearance and focus for droplists, radio buttons, etc
		for (i=0; i<eip_fields.length; i++){
			eip_fields[i].className = '';
			current_focus = false;
			($("SaveButton_"+eip_fields[i].parentNode.className)) ? eip_fields[i].parentNode.removeChild($("SaveButton_"+eip_fields[i].parentNode.className)) : null;
			($("CancelButton_"+eip_fields[i].parentNode.className)) ? eip_fields[i].parentNode.removeChild($("CancelButton_"+eip_fields[i].parentNode.className)) : null;
		}
	}
}

function droplistItems(result, container) {
	// get all links within 'container' element, and display the clicked item's text in 'result' element
	var d_items = container.getElementsByTagName('a');
	for (i=0; i<d_items.length; i++) {
		d_items[i].onclick = function () {
			var change = this.innerHTML
			result.innerHTML = change;
			saveChange(change, "access");
			return false;
		}
	}
}

function eip_commandButtons(el) {
	for (i=0; i<eip_fields.length; i++){
		// remove any existing command buttons
		($("SaveButton_"+eip_fields[i].parentNode.className)) ? eip_fields[i].parentNode.removeChild($("SaveButton_"+eip_fields[i].parentNode.className)) : null;
		($("CancelButton_"+eip_fields[i].parentNode.className)) ? eip_fields[i].parentNode.removeChild($("CancelButton_"+eip_fields[i].parentNode.className)) : null;
	}
	// add SAVE and CANCEL buttons elements beside this LI element
	var thisParent = el.parentNode;

	// Save button
	var saveButton_link = document.createElement('a');
	var saveButton_cap 	= document.createElement('img');
	var saveButton_text = document.createTextNode('Save');

	saveButton_link.className = "grey smallButton";
	saveButton_link.id = "SaveButton_"+thisParent.className;
	saveButton_link.setAttribute('href','#_bottom');
	saveButton_cap.setAttribute('src','images/button_cap_grey.gif');
	saveButton_cap.setAttribute('alt','');

	saveButton_link.appendChild(saveButton_cap);
	saveButton_link.appendChild(saveButton_text);
	saveButton_link.onclick = function () {
		var change = el.value;
		var which_field = el.name;
		saveChange(change, which_field);
		$('original_details_'+thisParent.className).value = change;
		return false;
	}

	// Cancel button
	var cancelButton_link 	= document.createElement('a');
	var cancelButton_cap 	= document.createElement('img');
	var cancelButton_text 	= document.createTextNode('Cancel');

	cancelButton_link.className = "grey smallButton";
	cancelButton_link.id = "CancelButton_"+thisParent.className;
	cancelButton_link.setAttribute('href','#_bottom');
	cancelButton_cap.setAttribute('src','images/button_cap_grey.gif');
	cancelButton_cap.setAttribute('alt','');

	cancelButton_link.appendChild(cancelButton_cap);
	cancelButton_link.appendChild(cancelButton_text);
	cancelButton_link.onclick = function () {$('details_'+thisParent.className).value = $('original_details_'+thisParent.className).value; eip_fieldFX(); return false;} // cancel restores field to original content via hidden input

	// Append buttons
	thisParent.appendChild(saveButton_link);
	thisParent.appendChild(cancelButton_link);

}

//==============================	RATINGS =======================

function showRating(container) {
	ratingStars = $(container).getElementsByTagName('img');
	for (i=0; i<ratingStars.length; i++) {
		ratingStars[i].onmouseover = (function(i) {return function() {rateThis(i)}})(i);
		ratingStars[i].onmouseup =  (function(i) {return function() {saveRating(i);}})(i);
	}
}

function freezeRating() {
	for (i=0; i<ratingStars.length; i++) {
		ratingStars[i].onmouseover = null;
		ratingStars[i].onmouseup = null;
	}
	// Thank you
	$('message').innerHTML = "Thanks for rating!";
}

function rateThis(currentRating) {
	var current;
	//reset all stars
	for (i=0; i<ratingStars.length; i++) {
		current = ratingStars[i].src.slice(0,ratingStars[i].src.lastIndexOf('_'));
		ratingStars[i].src = current + "_off.gif";
	}
	//hilite up to current star
	for (i=0; i<=currentRating; i++) {
		current = ratingStars[i].src.slice(0,ratingStars[i].src.lastIndexOf('_'));
		ratingStars[i].src = current + "_on.gif";
	}
}
function thumbnailCommands() {
	/*
	if ($('scene_pic')) {
		$('scene_pic').onmouseover = function() {$('thumbnailCommands').className = "on";};
		$('scene_pic').onmouseout = function() {$('thumbnailCommands').className = "off";};
		$('thumbnailCommands').onmouseover = function() {$('thumbnailCommands').className = "on";};
	}*/
}

//==============================	MISCELLANEOUS =======================
// expand / collapse toggles




//###############################################################################################################################//
//START OF OTHER STUFF

function submitStepOne() {

	if (cap_error == "mismatch") {
		image_sid = Math.random()*100;
		document.getElementById("captcha").src="../../php/scenecaster/securimage_show.php?sid="+image_sid;
		document.getElementById("image").className = "error";
		document.getElementById("image_code").value = "";
	} else if (cap_error == false) {
		document.getElementById("image").className = "";
	}
	//alert(email_error);
	if (email_error == "mismatch") {
		document.getElementById("email1").className = "error";
		document.getElementById("email2").className = "error";
	} else if (email_error == "not_available") {
		document.getElementById("email1").className = "error";
		document.getElementById("email2").className = "error";
	} else if (email_error == "invalid") {
		document.getElementById("email1").className = "error";
		document.getElementById("email2").className = "error";
	} else if (email_error == false) {
		document.getElementById("email1").className = "";
		document.getElementById("email2").className = "";
	}
	if (password_error == "length") {
	} else if (password_error == "mismatch") {
	} else if (password_error == false) {
		document.getElementById("pass2").className = "";
		document.getElementById("pass1").className = "";
	}

	if (username_error == "length") {
		document.getElementById("user1").className = "error";
	} else if (username_error == "not_available") {
		document.getElementById("user1").className = "error";
	} else if (username_error == false) {
		document.getElementById("user1").className = "";
	}

	if (cap_error == false && email_error == false && username_error == false && password_error == false && is_error == false) {
		document.getElementById("register_messages").innerHTML = "";
		document.regform.submit();
	} else {
		document.getElementById("submit_button").innerHTML = "<a href='javascript:validateStepOneForm();' class='mediumButton mediumGrey'><img src='images/button_medium_cap_grey.gif' alt='' />Sign Up!</a>";
	}
}


function openMacEmail() {
	if (document.getElementById("mac_email").style.display == "block") {
		document.getElementById("mac_email").style.display = "none";
	} else {
		document.getElementById("mac_email").style.display = "block";
	}
}

function cancelMacEmail() {
	document.getElementById("mac_address").value = "";
	openMacEmail();
}

function showAvailability() {
	if (show_check_button != true) {
		show_check_button = true;
		document.getElementById("check_user_button").innerHTML = "<a href='javascript:checkUsername(true);' class='smallButton grey'><img src='images/button_cap_grey.gif' />Check availability</a>";
	}
}

function showSystem() {
	document.getElementById("sys_require").style.display = "block";
}

function hideSystem() {
	document.getElementById("sys_require").style.display = "none";
}

/*
function validateContactUs(form) {

	var is_error = false;
	var email_error = true;
	email_error = validateEmail();

	if (email_error == false){
		document.getElementById("register_messages").style.display = "inline";
		document.getElementById("email").className = "error";
	} else {
		document.getElementById("email").className = "";
	}

	if (document.getElementById("subject").value == "") {
		document.getElementById("register_messages").style.display = "inline";
		document.getElementById("subject").className = "error";
		is_error = true;
	} else {
		document.getElementById("subject").className = "";
	}

	if (document.getElementById("message").value == "") {
		document.getElementById("register_messages").style.display = "inline";
		document.getElementById("message").className = "error";
		is_error = true;
	} else {
		document.getElementById("message").className = "";
	}

	if(email_error == false) {
		document.getElementById("register_messages").innerHTML = "Invalid email address.";
		return false;
	} else if(is_error == true) {
		document.getElementById("register_messages").innerHTML = "Please fill out the missing fields.";
		return false;
	} else if(is_error == false && email_error == true) {
		return true;
	}
}

function submitContactUs() {
	//to = "owenw@view22.com";
	to = "support@scenecaster.com";
	from = document.getElementById("email").value;
	subject = document.getElementById("subject").value;
	message = "Site feedback: <br /><br />" + document.getElementById("message").value;
	sendEmail(to, from, subject, message);
}



function validateEmail() {
	var email_error = false;
	var str = document.getElementById("email").value;
	var at="@";
	var dot=".";
	var lat=str.indexOf(at);
	var lstr=str.length;
	var ldot=str.indexOf(dot);

	if (document.getElementById("email").value == "") {
		email_error = true;
	} else if (str.indexOf(at)==-1){
		email_error = true;
	} else if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		email_error = true;
	} else if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		email_error = true;
	} else if (str.indexOf(at,(lat+1))!=-1){
		email_error = true;
	} else if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		email_error = true;
	} else if (str.indexOf(dot,(lat+2))==-1){
		email_error = true;
	} else if (str.indexOf(" ")!=-1){
		email_error = true;
	}
	if(email_error==true){
		return false;
	} else {
		return true;
	}

}
*/

function validatePasswordMyProfile() {

	if (document.getElementById("new_password").value == "") {
		document.getElementById("pass1").className="error";
		return false;
	}

	if (document.getElementById("new_password").value.length < 4 || document.getElementById("new_password").value.length > 12) {
		document.getElementById("pass1").className="error";
		return false;
	}

	if (document.getElementById("new_password_repeat").value == "") {
		document.getElementById("pass2").className="error";
		return false;
	}

	if (document.getElementById("new_password").value != document.getElementById("new_password_repeat").value) {
		document.getElementById("pass1").className="error";
		document.getElementById("pass2").className="error";
		return false;
	}

	submitNewPassword();
	return true;
}

function validateInfoMyProfile() {

	if (document.getElementById("first_name").value == "") {
		document.getElementById("email_message").style.display = "inline";
		document.getElementById("first_name").className = "error";
		document.getElementById("email_message").innerHTML = "Please enter a first name.";
		return false;
	} else if(document.getElementById("last_name").value == "") {
		document.getElementById("first_name").className = "";
		document.getElementById("email_message").style.display = "inline";
		document.getElementById("last_name").className = "error";
		document.getElementById("email_message").innerHTML = "Please enter a last name.";
		return false;
	}

	var is_error = validateEmail();

	var ValidChars = "0123456789()-#ext. ";
	 var IsNumber=true;
	 var Char;
	for (i = 0; i < document.getElementById("phone").value.length && IsNumber == true; i++)
		{
		Char = document.getElementById("phone").value.charAt(i);
		if (ValidChars.indexOf(Char) == -1)
		{
			IsNumber = false;
			document.getElementById("email_message").style.display = "inline";
			document.getElementById("phone").className = "error";
		}
	}

	if(is_error == true) {
		document.getElementById("email_message").innerHTML = "Invalid Email.";
		return false;
	} else if(is_error == false) {
		if(IsNumber == false) {
			document.getElementById("email_message").innerHTML = "Invalid character in phone number field.";
			return false;
		} else if(IsNumber == true) {
			return true;
		}
	}
}

function deletedMyScenes() {
	if (total_scenes > 0) {
		if (row_start == total_scenes)  {
			myscenes_Previous(row_start);
		} else {
			if (row_start + row_limit >= total_scenes)  {
				row_end = total_scenes;
				document.getElementById("myscenes_next").src = "images/myscenes_next_disabled.gif";
				document.getElementById("myscenes_row_info").innerHTML = "| "+(row_start+1)+" - " +row_end+" of "+total_scenes+" |";
			} else {
				row_end = row_start + row_limit;
				document.getElementById("myscenes_next").src = "images/myscenes_next.gif";
				document.getElementById("myscenes_row_info").innerHTML = "| "+(row_start+1)+" - " +row_end+" of "+total_scenes+" |";
			}
		}
	}
}

function nextImage() {
	if (pic_index+1==num_pics) {
		pic_index = 0;
	} else {
		pic_index++;
	}
	document.getElementById("scene_pic").src = scene_images[pic_index];
}

function previousImage() {
	if (pic_index==0) {
		pic_index = num_pics - 1;
	} else {
		pic_index--;
	}
	document.getElementById("scene_pic").src = scene_images[pic_index];
}

function AppInstalled(strServer){

	var isIE = (navigator.appName.indexOf("Microsoft Internet Explorer")>-1);

	try{
		var retAppInstalled = false;
		var strUser = "";

		if (!isIE){
			var v22Plugin = navigator.plugins["SceneCaster"];
			if (v22Plugin!=null && typeof(v22plugin) != undefined) {
				var v22pluginDesc = v22Plugin.description;
				strUser = (v22pluginDesc.indexOf("Version: ")!=-1) ? v22pluginDesc.substring(v22pluginDesc.indexOf("Version: ")+9, v22pluginDesc.length) : "";
				retAppInstalled = (strUser=="") ? false : true;
				var strUser_Array = strUser.split(".");
			}
		} else {
			//alert("IS IE.. creating object");
			var v22Object = new ActiveXObject("View22.View22RTEv4");
			/*if(v22Object) {
				alert("created");
			} else {
				alert("failed to create");
			}*/
			if (v22Object != null){
				retAppInstalled = true;
				strUser = v22Object.GetRTEInfo();
				//alert(strUser);
				var strUser_Array = strUser.split(",");
			}
		}

		if (retAppInstalled) {
			var strServer_Array = strServer.split(",");

			if(parseInt(strUser_Array[0]) > parseInt(strServer_Array[0])) {
				retAppInstalled=true;
			} else if(parseInt(strUser_Array[0]) == parseInt(strServer_Array[0])) {
				if(parseInt(strUser_Array[1]) > parseInt(strServer_Array[1])) {
					retAppInstalled=true;
				} else if(parseInt(strUser_Array[1]) == parseInt(strServer_Array[1])) {
					if(parseInt(strUser_Array[2]) > parseInt(strServer_Array[2])) {
						retAppInstalled=true;
					} else if(parseInt(strUser_Array[2]) == parseInt(strServer_Array[2])) {
						retAppInstalled=true;
					} else {
						retAppInstalled=false;
					}
				} else {
					retAppInstalled=false;
				}
			} else {
				retAppInstalled=false;
			}

			//attempt to destroy the v22Object
			v22Object.Quit();
			v22Object.Application.Quit();
			v22Object = null;
		}
	}catch(err){
		//alert(err);
		try{
			//CollectGarbage();
		}catch(err){}
	}

	return retAppInstalled;
}

function launchScene(project_id, scene_type) {
	var bAppInstalled = AppInstalled(strReqVersion);
	var refUrl = "designer/scenecaster_system_check.php?project_id="+project_id+"&mode_id=1&scene_type="+scene_type;
	
	if (bAppInstalled) {
		OpenApp(refUrl);
	} else {
		//write the refUrl cookie
		var cookie_date = new Date();  // current date & time
		cookie_date.setTime ( cookie_date.getTime() + (60*60*24*30) );
		document.cookie = "sc_refurl="+document.location.href+"; expires=" + cookie_date.toGMTString();
		location.href = "install.php?refUrl="+encodeURIComponent(refUrl);
	}
}

function refresh_page() {
	location.reload(true);
}
function showReport(pid) {
	alertObject({'yes':["sendReport("+pid+"); killAlert();","Ok"], 'no':[null,null], 'cancel':["killAlert();","Cancel"]},'Report',"Please tell us why you think this Scene is inappropriate. <br><input id='report' type='text' class='focusedField' />");
}
