//======================================================================================================================
// Toolbar Creation
//======================================================================================================================

// original inarray() function from Code Lab (http://code.mikebrittain.com/?p=8)
// modified by (http://andrew.hedges.name/experiments/javascript_optimization/in_array.html)

	Array.prototype.in_array = function(search_term) {
	  var i = this.length;
	  if (i > 0) {
		 do {
			if (this[i] === search_term) {
			   return true;
			}
		 } while (i--);
	  }
	  return false;
	}

	function loadToolbar (startView) {
		create_rollovers();
		bind_core_tabs();
		start_active_toolbar(startView);
	}

	var preloaded_images = new Array();
	var normal_images = new Array();
	var common_icon_dir = "images/";

	function create_rollovers () {
		// loop through every image in the page, save in icon array
		normal_images = document.getElementsByTagName('img');

		// if the image has the special classname then preload and attach mouse events to it
		for (i=0; i<normal_images.length; i++) {
			if (normal_images[i].className == "api_icon") {
				// parse out the core image name
				var full_name = normal_images[i].src;
				var parsed_name = (full_name.slice(full_name.lastIndexOf("/")+1,full_name.length-7))
				var file_extension = full_name.slice(full_name.length-4, full_name.length);

				// preload icons
				preloaded_images[i] = document.createElement('img');
				preloaded_images[i].setAttribute('src',common_icon_dir + parsed_name + '_hv' + file_extension);

				// attatch events
				normal_images[i].onmouseover=function()	{icon_over  (this);};
				normal_images[i].onmouseout =function()	{icon_out   (this);};
				normal_images[i].onmousedown=function()	{icon_down  (this);};
				normal_images[i].onmouseup  =function()	{icon_up    (this);};

			}
		}
	}

	function write_tip (icon, iconText) {
		if (icon != "Default") {
			/*document.getElementById("icon_name").innerHTML = icon+": ";
			document.getElementById("icon_description").innerHTML = iconText;		*/
		} else {
			/*document.getElementById("icon_name").innerHTML = "Tip:";
			document.getElementById("icon_description").innerHTML = "double click on an object for extra options";*/
		}
	}

	function icon_down (icon) {
		switch(icon.getAttribute('alt')) {
			case "Open":					_System.dispatch("PromptOpenScene"); break;
			case "New":		                New();              break;
			case "Exit":			        Exit();             break;
			case "Save":			        _System.dispatch("PromptSaveScene"); break; // OpenSave();
			case "Save As":			        OpenSaveAs();       break; //_System.dispatch("PromptSaveSceneAs"); break; 
			case "Undo":			        Undo();             break;
			case "Redo":			        Redo();             break;
			case "Print":			        Print();            break;
			case "Duplicate":		        Duplicate();        break;
			case "Delete":			        Delete();           break;
			case "Draw Walls":	            Draw();             break;
			case "Draw Exterior":           DrawExterior();     break;
			case "Insert Door":	            InsertDoor();       break;
			case "Insert Window":           InsertWindow();     break;
			case "Insert Light":            InsertLight();      break;
			case "Zoom In":		            StartZoom('in');    break;
			case "Zoom Out":		        StartZoom('out');   break;
			case "Zoom All":		        ZoomAll();	        break;
			case "Help":			        Help();             break;
			case "Rotate Clockwise":        StartRotate('CW');	break;
			case "Rotate Counterclockwise": StartRotate('CCW'); break;
			case "Move Up":		            StartMove('up');    break;
			case "Move Down":		        StartMove('down');  break;
			case "Increase Lighting":       StartIncreaseDecreaseLight('increase'); break;
			case "Decrease Lighting":       StartIncreaseDecreaseLight('decrease'); break;
			case "Camera Map":	            CameraMap();        break;
			case "Snapshot":		        Snapshot();         break;
			case "Scale Object":	        StartResizing();    break;
			case "Model Viewer":	        ModelViewer();      break;
			case "Full Screen":	            fullScreen();       break;
			case "Link":	                objectLinkMenu();   break;
			default: break;
		}
	}

	function icon_over (icon) {
		var full_name = icon.src;
		var parsed_name = (full_name.slice(full_name.lastIndexOf("/")+1,full_name.length-7));
		var file_extension = full_name.substring(full_name.length-4, full_name.length);
		icon.src = common_icon_dir + parsed_name +"_hv" + file_extension;

		switch(icon.getAttribute('alt')) {
			case "New":         write_tip('New Scene','start from a blank canvas and draw your scene from scratch'); break;
			case "Exit":		write_tip('Exit','safely close the application and return to Scenecaster'); break;
			case "Save":		write_tip('Save','save your project'); break;
			case "Save As":	    write_tip('Save As','save your project with a new name'); break;
			case "Undo":		write_tip('Undo','go back one step');	break;
			case "Redo":		write_tip('Redo','go forward one step');	break;
			case "Print":		write_tip('Print','print the current view of your project');	break;
			case "Duplicate":	write_tip('Duplicate','clone the selected object'); break;
			case "Delete":		write_tip('Delete','delete the selected object'); break;
			case "Draw Walls":  write_tip('Draw Walls','draw the walls for your scene');	break;
			case "Insert Door":	write_tip('Insert Door','insert a door into any wall'); break;
			case "Insert Window":write_tip('Insert Window','insert a window into any wall'); break;
			case "Insert Light":write_tip('Insert Light','insert a light source into your scene'); break;
			case "Zoom In":	    write_tip('Zoom In','zoom in on your scene to get a closer view'); break;
			case "Zoom Out":	write_tip('Zoom Out','zoom out from your scene to get a broader view'); break;
			case "Zoom All":	write_tip('Zoom All','view your whole scene'); break;
			case "Help":		write_tip('Help','view the help window'); break;
			case "Rotate Clockwise": write_tip('Rotate Clockwise','rotate the selected object clockwise'); break;
			case "Rotate Counterclockwise":	write_tip('Rotate Counterclockwise','rotate the selected object counter-clockwise'); break;
			case "Move Up":	    write_tip('Move Up','move the selected object up'); break;
			case "Move Down":	write_tip('Move Down','move the selected object down'); break;
			case "Increase Lighting": write_tip('Increase Lighting','increase the brightness of the lighting'); break;
			case "Decrease Lighting": write_tip('Decrease Lighting','decrease the brightness of the lighting'); break;
			case "Camera Map":  write_tip('Camera Map','view the camera control panel'); break;
			case "Snapshot":	write_tip('Snapshot','take a picture of the scene from the current viewpoint'); break;
			case "Scale Object":write_tip('Scale Object','increase or decrease the size of the object'); break;
			case "Full Screen":	write_tip('Full Screen','Toggle Full Screen'); break;
			case "Link":	    write_tip('Object Linking','Link an object to a scene or to a URL'); break;
			default:				write_tip('Default');
		}
	}

	function icon_up (icon) {
		switch(icon.getAttribute('alt')) {
			case "Zoom In":		            StopZoom();     break;
			case "Zoom Out":		        StopZoom();     break;
			case "Rotate Clockwise": 		StopRotate();	break;
			case "Rotate Counterclockwise": StopRotate();   break;
			case "Move Up":		            StopMove();     break;
			case "Move Down":		        StopMove();     break;
			case "Increase Lighting":       StopIncreaseDecreaseLight(); break;
			case "Decrease Lighting":       StopIncreaseDecreaseLight(); break;
			default: break;
		}
	}

	function icon_out (icon) {
		var full_name = icon.src;
		var parsed_name = (full_name.slice(full_name.lastIndexOf("/")+1,full_name.length-7));
		var file_extension = full_name.substring(full_name.length-4, full_name.length);
		icon.src = common_icon_dir + parsed_name +"_nm" + file_extension;

		switch(icon.getAttribute('alt')) {
			case "Zoom In":		            StopZoom();     break;
			case "Zoom Out":		        StopZoom();     break;
			case "Rotate Clockwise": 		StopRotate();	break;
			case "Rotate Counterclockwise": StopRotate();   break;
			case "Move Up":		            StopMove();     break;
			case "Move Down":		        StopMove();     break;
			case "Increase Lighting":       StopIncreaseDecreaseLight(); break;
			case "Decrease Lighting":       StopIncreaseDecreaseLight(); break;
			default: break;
		}
		write_tip("Default");
	}


	function iconStopFunctions () {
		// exit any functions or modes the user is in
		// --* StopInserting() *-- should be here
		StopZoom();
		StopRotate();
		StopMove();
		StopIncreaseDecreaseLight();
	}


	////////////////////////////////////////////////////////////////////////////////////
	//						SWITCH BETWEEN TABS
	////////////////////////////////////////////////////////////////////////////////////

	// pre-existing tabs hardcoded since always required - new tabs are added to this array on the fly
	var tabsets = new Array("2d","3d","google");
	// ebay and amazon store # trackers
	var amazon_num = 1;
	var ebay_num = 1;

	function bind_core_tabs () {
		// required tabs functionality
		/*
		// requires closure to apply proper variable scope to 'i'
		for (var i=0;i<=2;i++ )	{
			var x = tabsets[i];
			document.getElementById('tab_' + x).onmouseup = function () {alert("clicked "+x),set_active_toolbar(x);};
		}*/

		document.getElementById('tab_' + tabsets[0]).onmouseup = function () {set_active_toolbar(tabsets[0]);};
		document.getElementById('tab_' + tabsets[1]).onmouseup = function () {set_active_toolbar(tabsets[1]);};
		document.getElementById('tab_' + tabsets[2]).onmouseup = function () {set_active_toolbar(tabsets[2]);};

	}

	function disable_toolbars() {
		// reset ALL tabs to OFF
		for (var i=0; i < tabsets.length; i++) {
			document.getElementById('tab_' + tabsets[i]).className = "tab off";
			document.getElementById('tab_' + tabsets[i] + '_cap').src = common_icon_dir + "tab_off_start.gif";
			document.getElementById('toolbar_' + tabsets[i]).style.display = "none";
			if (document.getElementById('store_' + tabsets[i])) {document.getElementById('store_' + tabsets[i]).style.display = "none";}
		}

	}

	function set_active_toolbar (view) {
		// turn off help if its on
		document.getElementById("Main_help_layer").style.display="none";

		// reset ALL tabs to OFF
		for (var i=0; i < tabsets.length; i++) {
			document.getElementById('tab_' + tabsets[i]).className = "tab off";
			document.getElementById('tab_' + tabsets[i] + '_cap').src = common_icon_dir + "tab_off_start.gif";
			document.getElementById('toolbar_' + tabsets[i]).style.display = "none";
			if (document.getElementById('store_' + tabsets[i])) {document.getElementById('store_' + tabsets[i]).style.display = "none";}
		}
		// turn selected tab ON
		document.getElementById('tab_' + view).className = "tab on";
		document.getElementById('tab_' + view + '_cap').src = common_icon_dir + "tab_on_start.gif";
		document.getElementById('toolbar_' + view).style.display = "block";
		if (document.getElementById('store_' + view)) {document.getElementById('store_' + view).style.display = "block";}

		var flash = (navigator.appName.indexOf ("Microsoft") !=-1)?window["Catalog"]:document["Catalog"];

		//_System.dispatch("setMode",view);


		if (view == "2d") { // 2D display mode
		  document.view22RTE.SetView(1);
			/*if (flash) {
				flash.set2D();
			}*/
			
			_System.dispatch("setMode",1);

			if (document.getElementById("print_layer").style.display=="block") {
				document.getElementById("print_layer").style.display="none";
			}

		} else if (view == "3d") { // 3D display mode
			document.view22RTE.SetView(2);
			/*if (flash) {
				flash.set3D();
			}*/
			
			_System.dispatch("setMode",2);

			if (document.getElementById("print_layer").style.display=="block") {
				document.getElementById("print_layer").style.display="none";
			}

		} else if (view == "google") { // google 3d warehouse
			document.view22RTE.SetView(4);
			_System.dispatch("setMode",4);

			if (document.getElementById("print_layer").style.display=="block") {
				document.getElementById("print_layer").style.display="none";
			}

		} else {
			_System.dispatch("setMode",2);
		}

	}

	function start_active_toolbar (view) {

		if (view == "2d") {
			_System.dispatch("setMode",1);
		} else {
			_System.dispatch("setMode",2);
		}

		// turn off help if its on
		document.getElementById("Main_help_layer").style.display="none";

		// reset ALL tabs to OFF
		for (var i=0; i < tabsets.length; i++) {
			document.getElementById('tab_' + tabsets[i]).className = "tab off";
			document.getElementById('tab_' + tabsets[i] + '_cap').src = common_icon_dir + "tab_off_start.gif";
			document.getElementById('toolbar_' + tabsets[i]).style.display = "none";
			if (document.getElementById('store_' + tabsets[i])) {document.getElementById('store_' + tabsets[i]).style.display = "none";}
		}
		// turn selected tab ON
		document.getElementById('tab_' + view).className = "tab on";
		document.getElementById('tab_' + view + '_cap').src = common_icon_dir + "tab_on_start.gif";
		document.getElementById('toolbar_' + view).style.display = "block";
		if (document.getElementById('store_' + view)) {document.getElementById('store_' + view).style.display = "block";}

	}

	function create_toolbar_tabs (newTabTitle, newTabReference, newTabType, tooltip) {
		// if not null, populate new tab and its' toolbar using DOM methods
		var testForTab = tabsets.in_array(newTabReference);
		if (newTabReference != null && testForTab == 0) {
			if (tabsets.length < 9) {
				//--------- CREATE TAB ------------------//
				var num_suffix = (newTabType == "Amazon") ? amazon_num++ : ebay_num++ ;

				var tabComponent_LINK 	= document.createElement('a');
				var tabComponent_IMG 	= document.createElement('img');
				var tabComponent_TITLE 	= document.createTextNode(newTabTitle);
				var tabComponent_SUFFIX = document.createElement('span');
				var tabComponent_SUFFIX_NUM 	= document.createTextNode(num_suffix); // when we can dynamically assign a number to this tab

				tabComponent_LINK.setAttribute('href', 'javascript:void(0)');
				tabComponent_LINK.id = "tab_" + newTabReference; // setting attribute doesnt always work with ID
				tabComponent_LINK.className = "tab off";			 // default off tab, turned on in set_active_toolbar
				tabComponent_LINK.setAttribute('title', tooltip + ' on ' + newTabType);

				tabComponent_IMG.setAttribute('src', common_icon_dir + 'tab_off_start.gif');
				tabComponent_IMG.id = "tab_" + newTabReference + "_cap";

				tabComponent_SUFFIX.className = "tab_suffix";
				tabComponent_SUFFIX.appendChild(tabComponent_SUFFIX_NUM);

				tabComponent_LINK.appendChild(tabComponent_IMG);
				tabComponent_LINK.appendChild(tabComponent_TITLE);
				//tabComponent_LINK.appendChild(tabComponent_SUFFIX);

				//--------- CREATE TOOLBAR ------------------//
				var toolbar_SHELL = document.createElement('div');
				var toolbar_BACKBUTTON = document.createElement('img');
				var toolbar_FORWARDBUTTON = document.createElement('img');
				var toolbar_CLOSEBUTTON = document.createElement('img');

				toolbar_SHELL.id = "toolbar_" + newTabReference;
				toolbar_SHELL.className = "toolbar";

				toolbar_BACKBUTTON.setAttribute('src', common_icon_dir + 'browser_back_disabled.gif');
				toolbar_BACKBUTTON.id = "toolbar_" + newTabReference + "_backButton";

				toolbar_FORWARDBUTTON.setAttribute('src', common_icon_dir + 'browser_forward_disabled.gif');
				toolbar_FORWARDBUTTON.id = "toolbar_" + newTabReference + "_forwardButton";

				toolbar_CLOSEBUTTON.setAttribute('src', common_icon_dir + 'browser_close_nm.gif');
				toolbar_CLOSEBUTTON.id = "toolbar_" + newTabReference + "_closeButton";
				toolbar_CLOSEBUTTON.className = "closeTabButton";

				//toolbar_SHELL.appendChild(toolbar_BACKBUTTON);
				//toolbar_SHELL.appendChild(toolbar_FORWARDBUTTON);
				toolbar_SHELL.appendChild(toolbar_CLOSEBUTTON);


				//--------- CREATE IFRAME STORE OVERLAY ------------------//
				var store_IFRAME = document.createElement('iframe');
				store_IFRAME.id = "store_" + newTabReference;
				store_IFRAME.src = 'store_'+ newTabType +'.php?product='+tooltip;

				// append new tab to tablist //////////////////////////////////
				document.getElementById('tab_list').appendChild(tabComponent_LINK);
				// append new toolbar to document
				document.getElementById('dynamic_toolbars').appendChild(toolbar_SHELL);
				// append new iframe to document
				document.getElementById('store_container').appendChild(store_IFRAME);

				// bind functionality to this new tab+toolbar /////////////////
				document.getElementById("tab_" + newTabReference).onmouseup = function () {set_active_toolbar(newTabReference) ;}; // changing tabs
				document.getElementById("toolbar_" + newTabReference + "_closeButton").onmouseup = function () {closeTab(newTabReference) ;}; // close functionality
				document.getElementById("toolbar_" + newTabReference + "_closeButton").onmouseover = function () {icon_over(this) ;};
				document.getElementById("toolbar_" + newTabReference + "_closeButton").onmouseout  = function () {icon_out(this) ;};

				// append the reference of this tab+toolbar to tracking array
				tabsets.push(newTabReference);
				//set this tab+toolbar as active
				set_active_toolbar(newTabReference);
			} else {
				alert("You need to close an existing store tab before making a new one.");
			}
		} else {
			// since object ID is the tab reference show the tab belonging to that ID
			set_active_toolbar(newTabReference);
		}
	}

	function closeTab (ref) {
		var thisIndex;
		var nextIndex;
		var nextTab;

		// If there are more shopping tabs to the right, go to the right-most one. If not, start moving left.
		// If there are no more shopping tabs, go to 3D View

		// grab this ref's index for removal
		for (var i=0; i<tabsets.length; i++) {
			(tabsets[i] == ref) ? thisIndex = i : thisIndex = thisIndex;
		}
		// if at the end, hilight THISINDEX-1, else hilight THISINDEX+1
		(tabsets[thisIndex+1] == undefined) ? nextIndex = thisIndex-1 : nextIndex = thisIndex+1;
		// extract name of new tab before destroying old one
		nextTab = tabsets[nextIndex];
		(nextTab == "google") ? nextTab = "3d" : nextTab = nextTab; // after shop tabs close, default to 3d view

		// destroy id from tracking array
		tabsets.splice(thisIndex, 1);
		// destroy tab
		document.getElementById('tab_' + ref).parentNode.removeChild(document.getElementById('tab_' + ref));
		// destroy toolbar
		document.getElementById('toolbar_' + ref).parentNode.removeChild(document.getElementById('toolbar_' + ref));
		// destroy store
		document.getElementById('store_' + ref).parentNode.removeChild(document.getElementById('store_' + ref));

		// refresh view
		set_active_toolbar(nextTab);
	}

    function Google_Back() {
        document.view22RTE.GoBack();
    }

    function Google_Forward() {
        document.view22RTE.GoForward();
    }

//======================================================================================================================
// RTE_Toolbar
//======================================================================================================================


	var swapTabMode = 2;
	var sceneName1 = "";
	var sceneDescription1 = "";
	var sceneTags1 = "";
	var sceneInspiredBy1 = "";
	var sceneAccess1 = "";
	var sceneType1 = "";
	var AddToMyFavorites1 = "";
	var	save_image_action = "";
	var save_before_new = false;

	function fullScreen() {
		document.getElementById("commerce_container").style.display = "none";
		document.getElementById("app").style.top = "0px";
		document.getElementById("app").style.left = "0px";
		document.getElementById("app").style.width = "100%";
		document.getElementById("app").style.height = "100%";
		document.getElementById("view22RTE").style.width = "100%";
		document.getElementById("view22RTE").style.height = "100%";
		document.getElementById("fullscreen_layer").style.display = "block";
	}

	function Uncomment(divid){
		//uncomment the object to get it to load
		var myHTML = document.getElementById(divid).innerHTML;
		myHTML = myHTML.replace("<!--","");
		myHTML = myHTML.replace("-->","");
		document.getElementById(divid).innerHTML = myHTML;
	}
	
    function CatalogLoaded(){
    }

	var link_menu_accessed = false;
	function objectLinkMenu(){

		//if it hasn't been accessed yet, uncomment it so the iframe loads
		if (!link_menu_accessed){
			Uncomment('link_menu_div');
			link_menu_accessed = true;
		}
		
	    var ids = getSelectedIds();

	    //get index of first object that isnt a floor/wall/etc. 
	    var i = 0;
	    while(i <= ids.length && (ids[i] == -1 || ids[i] == -2))
	        i += 2;
	    
	    //if i is outside the range of ids then no suitable object has been selected    
	    if(i > ids.length - 2)
	    {
	        alert("Please Select an Object");
	        return;
	    }
	    
	    var menu = document.getElementById('link_menu_div').style.display;
		document.getElementById('link_menu').src += "&instance_id=" + ids[i + 1];
		document.getElementById('link_menu_div').style.display = (menu == "none" || menu == '' || menu == null) ? "block" : "none";
	}

    function New(){
		if (user_id != "-1") {
			if (access_level == "public_view") {
				NewScene();
			} else {
				if (document.view22RTE.IsProjectDirty()) {
					document.getElementById("alert_new_layer").style.display="block";
				} else {
					NewScene();
				}
			}
		} else {
			 NewScene();
		}
    }

    function NewSave(){
		document.getElementById("alert_new_layer").style.display="none";
		save_before_new = true;
		set_active_toolbar("3d");
		document.view22RTE.SetView(2);
		OpenSave();
//		document.view22RTE.NewProject(0,false);
//		proj_exists=0;
//		mode=0;
//		document.view22RTE.SendAppMessage('MenuDispatch','2');
    }

    function NewNoSave(){
		document.getElementById("alert_new_layer").style.display="none";
		NewScene();
    }

    function NewCancel(){
		document.getElementById("alert_new_layer").style.display="none";
    }

    function NewScene(){
		set_active_toolbar("2d");
		document.view22RTE.SetView(1);
        mLengthFeet = 0;
        mLengthInches = 0;
        mWidthFeet = 0;
   	    mWidthInches = 0;
   	    mHeightFeet = 0;
  	    mHeightInches = 0;
        document.view22RTE.NewProject(0,0);
        proj_exists = 0;
        project_id = 0;
		Draw();
	}

    function Open(project){
		if (document.view22RTE.IsProjectDirty()) {
			document.getElementById("alert_open").src="alert_open.php?project="+project;
			document.getElementById("alert_open_layer").style.display="block";
		} else {
			OpenConfirm(project);
		}
    }

    function OpenConfirm(project){
		document.getElementById("alert_open_layer").style.display="none";
        document.view22RTE.OpenProject(project,0);
        project_id = project;
        proj_exists=1;
    }

    function OpenDesign(project){
		document.getElementById("alert_open_layer").style.display="none";
        document.view22RTE.OpenProject(project,0);
        project_id = project;
        proj_exists=1;
    }

    function OpenCancel(){
		document.getElementById("alert_open_layer").style.display="none";
    }

/*    function OpenSave() {
        if (own_project == "true") {
			if (proj_exists == 0) {
				var flash = (navigator.appName.indexOf ("Microsoft") !=-1)?window["Catalog"]:document["Catalog"];
				flash.onExpandDesignsSaveClick();
				SaveAs();
			} else {
				document.view22RTE.Save(1);
			}
        } else {
			OpenSaveAs();
		}
    }
*/

	function OpenSave() {
        
		if(user_id==-1) {
			alert("You must be logged in to save a project.");
		} else {

			if (save_before_new == true && proj_exists == 0) {
				//var flash = (navigator.appName.indexOf ("Microsoft") !=-1)?window["Catalog"]:document["Catalog"];
				//flash.onExpandDesignsSaveClick();
				OpenSaveAs();
			} else if (save_before_new == true && proj_exists != 0) {
				if (own_project == "true") {
					Save();
				} else {
					//var flash = (navigator.appName.indexOf ("Microsoft") !=-1)?window["Catalog"]:document["Catalog"];
					//flash.onExpandDesignsSaveClick();
					OpenSaveAs();
				}
			} else if (proj_exists == 0) {
				//var flash = (navigator.appName.indexOf ("Microsoft") !=-1)?window["Catalog"]:document["Catalog"];
				//flash.onExpandDesignsSaveClick();
				OpenSaveAs();
			} else {
				if(access_level == "public") {
					if (own_project == "true") {					    
						document.view22RTE.Save(1);
						document.getElementById("progress_bar_save_layer").style.display = "block";
					} else {
						OpenSaveAs();
					}
				} else if (access_level == "public_view") {
					if (own_project == "true") {
						//var unpaid = checkForGoods();
						document.view22RTE.Save(1);
						document.getElementById("progress_bar_save_layer").style.display = "block";
					} else {
						alert("Sorry the owner of this project has disabled saving.");
					}
				} else if (access_level == "private") {
					if (own_project == "true") {
						//var unpaid = checkForGoods();
						document.view22RTE.Save(1);
						document.getElementById("progress_bar_save_layer").style.display = "block";
					}
				}
			}
		}
    }

    function Save(){
        alert(proj_exists);
        if (proj_exists == 0) {
            SaveAs();
        } else {
			//var unpaid = checkForGoods();
            document.view22RTE.Save(1);
			document.getElementById("progress_bar_save_layer").style.display = "block";
        }
    }

    function OpenSaveAs() {

		if(user_id==-1) {
			alert("You must be logged in to save a project.");
		} else {
			if(access_level == "public_view") {
				if(own_project == "false") {
					alert("Sorry the owner of this project has disabled saving.");
				} else {
					_System.dispatch("PromptSaveSceneAs");
					//var flash = (navigator.appName.indexOf ("Microsoft") !=-1)?window["Catalog"]:document["Catalog"];
					//flash.onExpandDesignsSaveClick();
				}
			} else {
				_System.dispatch("PromptSaveSceneAs");
				//var flash = (navigator.appName.indexOf ("Microsoft") !=-1)?window["Catalog"]:document["Catalog"];
				//flash.onExpandDesignsSaveClick();
			}
		}
    }

    function SaveAs(sceneName, sceneDescription, sceneTags, sceneInspiredBy, sceneAccess, AddToMyFavorites, viewerType){

		document.getElementById("progress_bar_save_layer").style.display = "block";

		sceneName1 = sceneName;
        sceneDescription1 = sceneDescription;
        sceneTags1 = sceneTags;
        sceneInspiredBy1 = sceneInspiredBy;
        sceneAccess1 = sceneAccess;
		sceneType1 = scene_type; // js variable from app page
        AddToMyFavorites1 = AddToMyFavorites;
		viewerType1 = viewerType;

		if (sceneDescription1 == "null") {
			sceneDescription1 = "";
		}

		if (sceneTags1 == "null") {
			sceneTags1 = "";
		}

		if (sceneInspiredBy1 == "null") {
			sceneInspiredBy1 = "";
		}

		if (sceneAccess1 == "null") {
			sceneAccess1 = "public";
		}
		
		//Check for a blank scene
		if(checkForWalls())
		{
			
			/*var unpaid = checkForGoods();
			if(unpaid != "" && unpaid != false)
			{
				_System.dispatch('dialog',{
						name : "buyGoods",
						title: 'Buy Goods',
						type: "DYNAMIC",
						src: 'paypal/generate_order.php',
						styles: {'top':200, 'left':400, 'width':400, 'height':300}
					});
			}
			else
			{*/
		    	document.view22RTE.SaveAs(sceneName1,1,1);
				access_level = sceneAccess1;
		        proj_exists = 1;
			//}
		}
		else
		{
			alert("Invalid room. Please draw walls in 2D mode to save your Scene.");
			document.getElementById("progress_bar_save_layer").style.display = "none";
			set_active_toolbar("2d");
		}
    }
	
	function checkForWalls()
	{
		var object_list = document.view22RTE.GetObjectIDs();
		if(object_list.indexOf("-2") == -1)
		{
			return false;
		}
		else
		{
			return true;
		}
	}
	
	function checkForGoods()
	{
		//var object_list = "9897, 1, 9896, 9894";
		var object_list = document.view22RTE.GetObjectIDs();
		if(object_list == "" || object_list == null)
		{
			return false;
		}
		else
		{
		
			var myRequest = new Request({
				url: 'paypal/check_goods.php', 
				method: 'post', 
				async: false
				}).send('object_list='+object_list);

			return myRequest.response.text;

		}
	}
	
    function SaveComplete(project_id2,is_new_project){
		
		//alert("save complete");
		ownerPid = project_id;
		project_id = project_id2;
		
		
		var baseName = web_url + "/app/projectimages/2D_" + project_id + "_0_";
        var detailsUrl = "http://www.scenecaster.com/web/scenecasts.php?project_id=" + project_id;

		var sceneIdEncoded  = escape(project_id);
		var userIdEncoded   = escape(user_id);
		var descripEncoded  = escape(sceneDescription1);
		var tagsEncoded     = escape(sceneTags1);
		var inspireEncoded  = escape(sceneInspiredBy1);
		var accessEncoded   = escape(sceneAccess1);
		var typeEncoded     = escape(sceneType1)
        var favEncoded      = escape(AddToMyFavorites1);
        var ownerEncoded    = escape(ext_user_id);
		var ownerPidEncoded	= escape(ownerPid);
		if(is_new_project)
		{
			var viewerEncoded	= escape(viewerType1);
		}
		else
		{
			var viewerEncoded = "nochange";
		}
        
		parameters = "?scene_id="+sceneIdEncoded+"&user_id="+userIdEncoded+"&scene_description="+descripEncoded+"&scene_tags="+tagsEncoded+"&scene_inspiredby="+inspireEncoded+"&scene_access="+accessEncoded+"&scene_type="+typeEncoded+"&scene_favorite="+favEncoded+"&scene_owner="+ownerEncoded+"&owner_pid="+ownerPidEncoded+"&viewer_type="+viewerEncoded;

		var xmlhttp = null;

		if (window.XMLHttpRequest){
			//If IE7, Mozilla, Safari, etc: Use native object
			xmlhttp = new XMLHttpRequest();
		} else {
			if (window.ActiveXObject){
				//If IE6 or IE5
				xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			}
		}

		xmlhttp.open("GET","scenecaster_save_as.php"+parameters+"&salt="+(Math.random()*100),true);
		xmlhttp.send(null);

		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState==4) {

				if(is_new_project)
				{
					if(viewerType1 == "true")
						document.view22RTE.SavePanoViewer(baseName, detailsUrl, 400, 227);
					else
						document.view22RTE.SaveSceneWeaver(baseName, detailsUrl, 400, 227);
				}
				else
				{
					var xmlhttp2 = null;
		
					if (window.XMLHttpRequest){
						//If IE7, Mozilla, Safari, etc: Use native object
						xmlhttp2 = new XMLHttpRequest();
					} else {
						if (window.ActiveXObject){
							//If IE6 or IE5
							xmlhttp2 = new ActiveXObject("Microsoft.XMLHTTP");
						}
					}
		
					xmlhttp2.open("GET","get_view_type.php?project_id="+project_id2+"&salt="+(Math.random()*100),true);
					xmlhttp2.send(null);
		
					xmlhttp2.onreadystatechange = function() {
						if (xmlhttp2.readyState==4) {
		
							if(xmlhttp2.responseText == 1)
								document.view22RTE.SavePanoViewer(baseName, detailsUrl, 400, 227);
							else
								document.view22RTE.SaveSceneWeaver(baseName, detailsUrl, 400, 227);
						}
					}
				
				}
				
				//var filename = "";
				//filename = sceneIdEncoded.toString();
				proj_exists = 1;
				own_project = "true";
				modifier = user_id;

				save_image_action = "save";
				//document.view22RTE.SaveImage(144,104,-1,filename);

			}
		}

		/*if(facebook == true) {
			var xmlhttp2 = null;

			if (window.XMLHttpRequest){
				//If IE7, Mozilla, Safari, etc: Use native object
				xmlhttp2 = new XMLHttpRequest();
			} else {
				if (window.ActiveXObject){
					//If IE6 or IE5
					xmlhttp2 = new ActiveXObject("Microsoft.XMLHTTP");
				}
			}
			xmlhttp2.open("GET","../../../php/scenecaster/notify.php?project_id="+project_id,true);
			xmlhttp2.send(null);
			//document.getElementById("content_loader").src = "../../../php/scenecaster/notify.php?project_id="+project_id;
			xmlhttp2.onreadystatechange = function() {
				if (xmlhttp2.readyState==4) {
					//alert("notification sent");
				}
			}
		}*/
    }

	function OnSaveCameraCubeMapsComplete()
	{
		//alert("save cube maps complete");
		document.view22RTE.SaveImage(144,104,-1, project_id.toString());	
	}
	function OnSavePanoViewerComplete()
	{
		//alert("save PanoViewer complete");
		
		var baseName = web_url + "/app/projectimages/2D_" + project_id + "_0_";
		document.view22RTE.SaveCameraCubeMaps(baseName, 800, 95);
	}
	
	function OnSaveSceneWeaverComplete()
	{
		//alert("save SceneWeaver complete");
		document.view22RTE.SaveImage(144,104,-1, project_id.toString());
	}
	

    function Draw(){
        document.view22RTE.ClientCommand(2,1101);
        //document.view22RTE.SendAppMessage('MenuDispatch','2');
    }

    function DrawExterior(){
        document.view22RTE.ClientCommand(2,1101);
        //document.view22RTE.SendAppMessage('MenuDispatch','2');
    }

    function Undo(){
        document.view22RTE.Undo();
    }

    function Redo(){
        document.view22RTE.Redo();
    }

    function Delete(){
        document.view22RTE.Cut();
    }

    function Copy(){
        document.view22RTE.Copy();
    }

    function Paste(){
        document.view22RTE.Paste();
    }

    function Duplicate(){
        document.view22RTE.Copy();
        document.view22RTE.Paste();
    }

    var zoom;

    function StartZoom(type){
        if(type=='out') {
            ZoomOut();
        } else {
            ZoomIn();
        }
    }

    function ZoomOut(){
        //document.view22RTE.Zoom('out');
        document.view22RTE.ClientCommand(2,28);
        zoom = setTimeout("ZoomOut()", 25);
    }

    function ZoomIn(){
        //document.view22RTE.Zoom('in');
        document.view22RTE.ClientCommand(2,27);
        zoom = setTimeout("ZoomIn()", 25);
    }

    function StopZoom(){
        clearTimeout(zoom);
    }

    function ZoomAll(){
        document.view22RTE.ClientCommand(2,29);
    }

    var rotate;

    function StartRotate(direction){
        if(direction=='CW') {
            RotateCW();
        } else {
            RotateCCW();
        }
    }

    function RotateCW(){

        var direction = "";
        reset_degree = reset_degree -1;
        var instancID = view22RTE.SendAppMessage("GetSelectedObjects","");
        id = instancID.substring(instancID.indexOf(",")+1, instancID.length);
		id = id.substring(0,id.indexOf(","));
        command = "instanceID="+id+" evalConstraints=false degrees="+direction+"2";
        view22RTE.SendAppMessage("Rotate",command);
        rotate = setTimeout("RotateCW()", 20);
    }

    function RotateCCW(){

        var direction = "-";
        reset_degree = reset_degree +1;
        var instancID = view22RTE.SendAppMessage("GetSelectedObjects","");
        id = instancID.substring(instancID.indexOf(",")+1, instancID.length);
		id = id.substring(0,id.indexOf(","));
        command = "instanceID="+id+" evalConstraints=false degrees="+direction+"2";
        view22RTE.SendAppMessage("Rotate",command);
        rotate = setTimeout("RotateCCW()", 20);
    }

    reset_degree = 0;

    function StopRotate(){
        clearTimeout(rotate);
    }

    var light;

    function StartIncreaseDecreaseLight(direction){
        if(direction=='increase') {
            IncreaseLight();
        } else {
            DecreaseLight();
        }
    }

    function IncreaseLight(){
        document.view22RTE.ClientCommand(2,2063);
        light = setTimeout("IncreaseLight()", 70);
    }

    function DecreaseLight(){
        document.view22RTE.ClientCommand(2,2064);
        light = setTimeout("DecreaseLight()", 70);
    }

    function StopIncreaseDecreaseLight(){
        clearTimeout(light);
    }

    function ZoomAll(){
        document.view22RTE.ClientCommand(2,29);
    }

    function InsertDoor(){
        var flash = (navigator.appName.indexOf ("Microsoft") !=-1)?window["Catalog"]:document["Catalog"];
        flash.setDoors();
    }

    function InsertWindow(){
        var flash = (navigator.appName.indexOf ("Microsoft") !=-1)?window["Catalog"]:document["Catalog"];
        flash.setWindows();
    }

    function Snapshot(){
		if(user_id==modifier) {
			name = document.view22RTE.HttpGet("",web_url+"/web/designer/Snapshot.php?project_id="+project_id,"","",false);
			name = name.replace(/\n/g, "")
			name = name.replace(/\r/g, "")
			document.view22RTE.SaveImage(-1,-1,-1,name);
			document.getElementById("alert_snapshot_layer").style.display="block";
		} else {
			alert("You must save the scene to take snapshots.");
		}
    }

	function SaveImageComplete(name){
		//alert("save Image complete");
		if (save_image_action == "print") {
			save_image_action = "";
			ShowPrintLayer(name);
		}
		if (save_image_action == "save") {
			save_image_action = "";
			//var flash = (navigator.appName.indexOf ("Microsoft") !=-1)?window["Catalog"]:document["Catalog"];
			//flash.onSaveComplete();

			document.getElementById("progress_bar_save_layer").style.display = "none";

			if(save_before_new == true) {
				alert("Your scene has been saved. A new scene will now load.");
				save_before_new = false;
				NewScene();
			} else {
				alert("Your scene has been saved.");
			}
		}
	}

    function ShowHelp() {
		document.getElementById("Main_help_layer").style.display="block";
    }

	var helpLocTracking = null;

    function ToggleHelp(jump) {
		disable_toolbars();
		(document.getElementById("Main_help_layer").style.display == "block") ? document.getElementById("Main_help_layer").style.display="none" : document.getElementById("Main_help_layer").style.display="block";
		(document.getElementById("Main_help_layer").src != "../help/3DEditor.php") ? document.getElementById("Main_help_layer").src = "../help/3DEditor.php" : null ;

		/*
		alert(helpLocTracking);

		if (helpLocTracking != null && jump == null) {
			document.getElementById("Main_help_layer").src = helpLocTracking;
		} else if (jump != null) {
			document.getElementById("Main_help_layer").src = "help/Help.html"+jump;
			helpLocTracking = document.getElementById("Main_help_layer").src;
		} else {
			document.getElementById("Main_help_layer").src = "help/Help.html";
		}*/

	}

	function QuickTips() {
        openPDFPopup(server+"/web/help/quickTips.pdf","QuickTips");
    }

    function About() {
        document.view22RTE.ClientCommand(2,1060);
    }

    function InsertLight(){
        document.view22RTE.ClientCommand(2,2060);
    }

    function CameraMap(){
        document.view22RTE.ClientCommand(2,2050);
    }

    function PreviousCamera(){
        document.view22RTE.SendAppMessage("ChangeCamera","Previous");
    }

    function NextCamera(){
        document.view22RTE.SendAppMessage("ChangeCamera","Next");
    }

    function TopDownCamera(){
        document.view22RTE.SendAppMessage("ChangeCamera","TopDown");
    }

    function Walkthrough(){
        document.view22RTE.ClientCommand(2,2050);
    }

    function Info(){
        //document.view22RTE.ClientCommand(2,2064);
    }

    function AddToGallery(objectids){
        document.view22RTE.AddToGallery(objectids);
    }

    function DragObject(objectid){
		if (document.view22RTE.GetView() == "1") {
			if (objectid == "7318" || objectid == "7319" || objectid == "7320" || objectid == "7321"){
				// insert door
				document.view22RTE.SendAppMessage('MenuDispatch','7.2.1.1.5');
			} else if (objectid == "7314" || objectid == "7315" || objectid == "7316" || objectid == "7317"){
				// insert window
				document.view22RTE.SendAppMessage('MenuDispatch','7.1.1.3')
			} else {
	            document.view22RTE.DragDropItem(objectid);		
			}
		} else {
            // insert object
            document.view22RTE.DragDropItem(objectid);
        }
    }

    var measurement =1;

    function ChangeMeasurement(){
        if (measurement ==1){
            document.view22RTE.SendAppMessage("SetMeasurement","imperial");
            measurement = 0;
        }
        else {
            document.view22RTE.SendAppMessage("SetMeasurement","metric");
            measurement = 1;
        }
    }

    function ReplaceObjects(id){
        if (id<1){
            return;
        }
        var objects = new String(window.parent.view22RTE.SendAppMessage("GetObjectsText",""));
        var parameters = "?id="+id+"&objects="+objects+"&project_id="+project_id;
        //alert(parameters);
        var response = window.parent.view22RTE.HttpGet("",server+"/web/designer/getObjectsToSwitch.php"+parameters,"","",false);
        //alert (response);
        objectArr = response.split(",");
        for(i=0;i<objectArr.length-1; i=i+2){
            if (Number(objectArr[i])!= Number(objectArr[i+1])){
                postData = "objectID=" + objectArr[i] + " newObjectID=" + objectArr[i+1];
                //alert(postData);
                document.view22RTE.SendAppMessage("replaceObject", postData);
            }
        }
    }

    var screenshot = "";
    var floorSelected = false;
    var counterSelected = false;

    function deSelect(objectInstanceID,objectID){
        if((objectID==-2) && (objectID==objectInstanceID)){
            Snapshot2(objectID);
        } else {
            if (objectID== -2) {
                floorSelected = true;
                counterSelected = false;
            } else if (objectID == -3) {
                counterSelected = true;
                floorSelected = false;
            } else {
                floorSelected = false;
                counterSelected = false;
            }
        }
    }

	var instanceID_previous = "";
    function sendToCommerce(objectInstanceID,objectID){
        //alert("inst: " + objectInstanceID + " id: " + objectID);
		if (objectID != "" && objectID != "-1" && objectID != "-2" && objectID != "-3" && objectID != "-4" && objectID != "-5") {
			if (objectInstanceID != instanceID_previous) {
				instanceID_previous = objectInstanceID;
				var tags = "";
				if(objectID < 0)
				{
                  tags = document.view22RTE.GetMetadata(objectInstanceID, "tags");
                }
				document.getElementById("commerce_container").src = "commerce.php?instance_id="+objectInstanceID+"&object_id="+objectID+"&tags="+tags;
			}
        }
    }

    function Snapshot2(arg){
        if(Number(arg)==-2){
            name = document.view22RTE.HttpGet("",web_url+"/web/designer/makePhoto.php?project_id="+project_id,"","",false);
            name = name.replace(/\n/g, "")
            name = name.replace(/\r/g, "")
			document.view22RTE.SaveImage(-1,-1,-1,name);
        }
    }

	function Print(){

		save_image_action = "print";
		if (window.XMLHttpRequest){
			//If IE7, Mozilla, Safari, etc: Use native object
			xmlhttp = new XMLHttpRequest();
		} else {
			if (window.ActiveXObject){
				//If IE6 or IE5
				xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			}
		}

		xmlhttp.open("GET","/web/designer/PrintImage.php",true);
		xmlhttp.send(null);

		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState==4) {
				name = xmlhttp.responseText;
				name = name.replace(/\n/g, "");
				name = name.replace(/\r/g, "");
				document.view22RTE.SaveImage(-1,-1,-1,name);
			}
		}
	}

	function ShowPrintLayer(name){
		document.getElementById("printer").src= web_url+"/web/designer/Print.php?print_id="+name;
	}

    function ModelViewer(){
		var instanceID = view22RTE.SendAppMessage("GetSelectedObjects","");
		var first_comma = instanceID.indexOf(",");
		var second_comma = instanceID.indexOf(",", first_comma + 1);
		if (second_comma == -1) {
	        id = instanceID.substring(first_comma + 1, instanceID.length);
		} else {
	        id = instanceID.substring(first_comma + 1, instanceID.indexOf(",", first_comma+1));
		}
		//alert(id);
		document.view22RTE.ShowModelViewer(id);
    }

    function ObjectSelections(){

        var instance_object_ids = view22RTE.SendAppMessage("GetSelectedObjects","");

        objectInstanceID = instance_object_ids.substring(instance_object_ids.indexOf(",")-1, instance_object_ids.length);
        objectID = instance_object_ids.substring(0,instance_object_ids.indexOf(","));

        if (objectID == "" || objectID == "-1" || objectID == "-2" || objectID == "-3" || objectID == "-4" || objectID == "-5") {

		} else {
			document.getElementById("object_selections").src= "ObjectChoices.php?instance_id="+objectInstanceID+"&object_id="+objectID;
        	document.getElementById("selections_container").style.display = "block";
        }
     }

    function ObjectSelectionsDC(objectInstanceID,objectID){

        if (objectID == "" || objectID == "-1" || objectID == "-2" || objectID == "-3" || objectID == "-4" || objectID == "-5") {
            //alert("You must be logged in to use this feature.");
        } else {
			document.getElementById("object_selections").src= "ObjectChoices.php?instance_id="+objectInstanceID+"&object_id="+objectID;
        	document.getElementById("selections_container").style.display = "block";
        }
     }

    function HideObjectChoices(){
		document.getElementById("object_selections").src= "/web/designer/images/spacer.gif";
        document.getElementById("selections_container").style.display = "none";
    }

    function ObjectNotes(arg_instance_id,arg_object_id){
        if(user_id!="-1") {

			var existing_comments = document.getElementById("view22RTE").GetComments(arg_instance_id);

			if (existing_comments == "") {
				document.getElementById("notes").src= "ObjectNotesAdd.php?instance_id="+arg_instance_id+"&object_id="+arg_object_id+"&comments="+existing_comments;
				document.getElementById("notes_container").style.display = "block";
				document.getElementById("object_selections").src= "/web/designer/images/spacer.gif";
				document.getElementById("selections_container").style.display = "none";

			} else {
				document.getElementById("notes").src= "ObjectNotesView.php?instance_id="+arg_instance_id+"&object_id="+arg_object_id+"&comments="+existing_comments;
				document.getElementById("notes_container").style.display = "block";
				document.getElementById("object_selections").src= "/web/designer/images/spacer.gif";
				document.getElementById("selections_container").style.display = "none";
			}

        } else {
			document.getElementById("selections_container").style.display = "none";
			document.getElementById("alert_logged_layer").style.display = "block";
        }
    }

    function HideNotes(){
		document.getElementById("notes").src= "/web/designer/images/spacer.gif";
		document.getElementById("notes_container").style.display = "none";
    }

    function HideGooglePanel(){
		document.getElementById("google_objects").src= "/web/designer/images/spacer.gif";
		document.getElementById("google_objects_container").style.display = "none";
    }

    function HideResizePanel(){
		document.getElementById("resize_objects").src= "/web/designer/images/spacer.gif";
		document.getElementById("resize_objects_container").style.display = "none";
    }

    function StartResizing(){
        document.view22RTE.ClientCommand(2,37);
    }

    function ResizeObject(objectID,objectInstanceID,x,y,z){
		var parameter_str = "?object_id="+objectID+"&instance_id="+objectInstanceID+"&x="+x+"&y="+y+"&z="+z;
		document.getElementById("resize_objects").src= "setObjectProperties.php"+parameter_str;
		document.getElementById("resize_objects_container").style.display = "block";
    }

    function GoogleObject(objectInstanceID, url, x, y, z){

        url = url.split("mid=");
        url = url[1].split("&");
        
        var mid = url[0];

        getGoogleMetaData(objectInstanceID, mid); //in ajax.js

        var parameter_str = "?instance_id="+objectInstanceID+"&x="+x+"&y="+y+"&z="+z;

		document.getElementById("object_selections").src= "/web/designer/images/spacer.gif";
		document.getElementById("selections_container").style.display = "none";
		document.getElementById("google_objects").src= "setGoogleObjectProperties.php"+parameter_str;
		document.getElementById("google_objects_container").style.display = "block";
        set_active_toolbar("3d");
    }
    
    function InternalObjectLoaded(instanceId, objectId)
    {
		document.getElementById("view22RTE").focus();
        SetInternalMetaData(objectId, instanceId);
    }
    
    function SetInternalMetaData(objectId, instanceId)
    {
        instanceId = instanceId.toString();
        instanceId = instanceId.split(",");
        
        var xmlhttp; 
			
		if (window.XMLHttpRequest)
		{
			//If IE7, Mozilla, Safari, etc: Use native object
			xmlhttp = new XMLHttpRequest();
		} 
		else if (window.ActiveXObject)
		{
			//If IE6 or IE5
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); 
		}

		var params = "objectId=" + objectId;
		xmlhttp.open("GET","../internal_metadata.php?" + params,true);
		xmlhttp.send(null);
		xmlhttp.onreadystatechange = function() 
		{
			if (xmlhttp.readyState==4) 
			{
				var metaData = xmlhttp.responseText;

				metaData = metaData.split("~;~");

				object_name_display	= metaData[0];
				tags				= metaData[1];
				description			= metaData[2];
				url					= metaData[3];
				provider            = metaData[4];

				//Populate Metadata so we dont have to go to DB again
				for(var i = 0; i < instanceId.length; i++)
				{
				    document.view22RTE.SetMetadata(instanceId[i], "type",      "internal");
				    document.view22RTE.SetMetadata(instanceId[i], "id",        objectId);
				    document.view22RTE.SetMetadata(instanceId[i], "name",      object_name_display);
				    document.view22RTE.SetMetadata(instanceId[i], "tags",      tags);
                }

				if(description != "")
					parent.document.view22RTE.SetMetadata(instanceId, "description", description);

				if(url != "")
					parent.document.view22RTE.SetMetadata(instanceId, "url", url);
				
				if(provider != "")
				    parent.document.view22RTE.SetMetadata(instanceId, "provider", provider);
				//*/

			}
        }
    }

    function OnOpenComplete()
    {
        HideProgressProject();
        
        if(swv_exists == 0 && project_id != 0)
            populateMissingMetaData();
    }
    
    function ShowProgress(context){

        //alert(context);
        if (context == "Initialize Application") {
            // Installing
            //document.all.progress_bar_initialize_layer.style.visibility = "visible";

        } else if (context == "Load Google Sketchup Object") {
            // Load Google Sketchup Object
			document.getElementById("progress_bar_model_layer").style.display = "block";
        } else if (context == "Load Project") {
            // Load Project
			document.getElementById("progress_bar_project_layer").style.display = "block";
        } else {
            // GENERIC PROGRESS
            //document.all.progress_bar_layer.style.visibility = "visible";
        }
     }

    function HideProgress(){
		document.getElementById("progress_bar_layer").style.display = "none";
		document.getElementById("progress_bar_model_layer").style.display = "none";
    }
    function HideProgressProject(){
		document.getElementById("progress_bar_project_layer").style.display = "none";
    }

    function HideAlerts(){
		document.getElementById("alert_open_layer").style.display = "none";
		document.getElementById("alert_logged_layer").style.display = "none";
		document.getElementById("alert_snapshot_layer").style.display = "none";
    }

    function OpenInterior(mLengthFeet,mLengthInches,mWidthFeet,mWidthInches,mHeightFeet,mHeightInches) {

		if(user_id=="-1") {

			if (confirm("Only registered SceneCasters can save, write reviews and fully enjoy the experience. Proceed if you just want a taste.")){

				var isIE = (navigator.appName.indexOf("Microsoft Internet Explorer")>-1);

				url = "designer/scenecaster_system_check.php?project_id=0&mode_id=3&scene_type=interior&mLengthFeet="+mLengthFeet+"&mLengthInches="+mLengthInches+"&mWidthFeet="+mWidthFeet+"&mWidthInches="+mWidthInches+"&mHeightFeet="+mHeightFeet+"&mHeightInches="+mHeightInches+"&salt="+(Math.random()*100);

				//if (AppInstalled() || !isIE) {

					if (window.appWin && window.appWin.open && !window.appWin.closed) {
						window.appWin.focus();
					} else {
						appWin = window.open(url, 'app', 'resizable=yes,width=1000,height=700,top=0,left=0');
						//appWin.opener = window.self;
						//appWin.opener.name = "app_win";
						//appWin.focus();
					}

				/*} else {

					//launch the installer
					url = url.replace("?","%3F");
					url = url.replace(/&/g,"%26");
					var pwlh=parent.window.location.href;

					if (pwlh.indexOf("?") > -1) {
						parent.window.location.href=pwlh+'&f=install&callingfn=OpenInterior&url='+url;
//						parent.window.location.href=pwlh+'&f=install&url='+url+'&name='+name+'&callingfn=OpenInterior';
					} else {
						parent.window.location.href=pwlh+'?f=install&callingfn=OpenInterior&url='+url;
//						parent.window.location.href=pwlh+'?f=install&url='+url+'&name='+name+'&callingfn=OpenInterior';
					}
				}*/

			} else {
				document.location.href = "step1.php"
			}

		} else { // if user_id != 0

			var isIE = (navigator.appName.indexOf("Microsoft Internet Explorer")>-1);

			url = "designer/scenecaster_system_check.php?project_id=0&mode_id=3&scene_type=interior&mLengthFeet="+mLengthFeet+"&mLengthInches="+mLengthInches+"&mWidthFeet="+mWidthFeet+"&mWidthInches="+mWidthInches+"&mHeightFeet="+mHeightFeet+"&mHeightInches="+mHeightInches+"&salt="+(Math.random()*100);

			if (AppInstalled() || !isIE){

				if (window.appWin && window.appWin.open && !window.appWin.closed) {
					window.appWin.focus();
				} else {
					appWin = window.open(url, 'app', 'resizable=yes,width=1000,height=700,top=0,left=0');
					//appWin.opener = window.self;
					//appWin.opener.name = "app_win";
					//appWin.focus();
				}

			}else{

				//launch the installer
				url = url.replace("?","%3F");
				url = url.replace(/&/g,"%26");
				var pwlh=parent.window.location.href;

				if (pwlh.indexOf("?") > -1) {
					parent.window.location.href=pwlh+'&f=install&callingfn=OpenInterior&url='+url;
//					parent.window.location.href=pwlh+'&f=install&url='+url+'&name='+name+'&callingfn=OpenInterior';
				} else {
					parent.window.location.href=pwlh+'?f=install&callingfn=OpenInterior&url='+url;
//					parent.window.location.href=pwlh+'?f=install&url='+url+'&name='+name+'&callingfn=OpenInterior';
				}
			}
		}
	}

	function OpenExterior(mLengthFeet,mLengthInches,mWidthFeet,mWidthInches) {

		if(user_id=="-1") {

			if (confirm("Only registered SceneCasters can save, write reviews and fully enjoy the experience. Proceed if you just want a taste.")){

				var isIE = (navigator.appName.indexOf("Microsoft Internet Explorer")>-1);

				if (AppInstalled() || !isIE){

					url = "designer/scenecaster_system_check.php?project_id=0&mode_id=3&scene_type=exterior&mLengthFeet="+mLengthFeet+"&mLengthInches="+mLengthInches+"&mWidthFeet="+mWidthFeet+"&mWidthInches="+mWidthInches+"&salt="+(Math.random()*100);

					if (window.appWin && window.appWin.open && !window.appWin.closed) {
						window.appWin.focus();
					} else {
						appWin = window.open(url, 'app', 'resizable=yes,width=1000,height=700,top=0,left=0');
						//appWin.opener = window.self;
						//appWin.opener.name = "app_win";
						//appWin.focus();
					}

				} else {

					url = "designer/scenecaster_system_check.php?project_id=0&mode_id=3&scene_type=exterior&mLengthFeet="+mLengthFeet+"&mLengthInches="+mLengthInches+"&mWidthFeet="+mWidthFeet+"&mWidthInches="+mWidthInches+"&salt="+(Math.random()*100);

					//launch the installer
					url = url.replace("?","%3F");
					url = url.replace(/&/g,"%26");
					var pwlh=parent.window.location.href;

					if (pwlh.indexOf("?") > -1) {
						parent.window.location.href=pwlh+'&f=install&url='+url+'&name='+name+'&callingfn=OpenExterior';
					} else {
						parent.window.location.href=pwlh+'?f=install&url='+url+'&name='+name+'&callingfn=OpenExterior';
					}
				}

			} else {
				document.location.href = "step1.php"
			}

		} else { // if user_id != 0

			var isIE = (navigator.appName.indexOf("Microsoft Internet Explorer")>-1);

			if (AppInstalled() || !isIE){

				url = "designer/scenecaster_system_check.php?project_id=0&mode_id=3&scene_type=exterior&mLengthFeet="+mLengthFeet+"&mLengthInches="+mLengthInches+"&mWidthFeet="+mWidthFeet+"&mWidthInches="+mWidthInches+"&salt="+(Math.random()*100);

				if (window.appWin && window.appWin.open && !window.appWin.closed) {
					window.appWin.focus();
				} else {
					appWin = window.open(url, 'app', 'resizable=yes,width=1000,height=700,top=0,left=0');
					//appWin.opener = window.self;
					//appWin.opener.name = "app_win";
					//appWin.focus();
				}

			} else {

				url = "designer/scenecaster_system_check.php?project_id=0&mode_id=3&scene_type=exterior&mLengthFeet="+mLengthFeet+"&mLengthInches="+mLengthInches+"&mWidthFeet="+mWidthFeet+"&mWidthInches="+mWidthInches+"&salt="+(Math.random()*100);

				//launch the installer
				url = url.replace("?","%3F");
				//url = url.replace(/&/g,"%26");
				var pwlh=parent.window.location.href;

				if (pwlh.indexOf("?") > -1) {
					parent.window.location.href=pwlh+'&f=install&url='+url+'&name='+name+'&callingfn=OpenExterior';
				} else {
					parent.window.location.href=pwlh+'?f=install&url='+url+'&name='+name+'&callingfn=OpenExterior';
				}
			}
		}
	}

    function OpenApp(url, name, installed) {

		var isIE = (navigator.appName.indexOf("Microsoft Internet Explorer")>-1);

		//if (AppInstalled() || !isIE){

			if(user_id=="-1") {
				//alert("Only Registered SceneCasters can Save, Write Reviews and Fully enjoy the experience. Proceed if you just want a taste.");
				OpenUnreg(url, name);
				return;
			} else {

				width = window.screen.width;
				height = window.screen.height;
				maxwidth = window.screen.availWidth;
				maxheight = window.screen.availHeight;
				
				if (window.appWin && window.appWin.open && !window.appWin.closed) {
					window.appWin.focus();
				} else {
					appWin = window.open(url, 'app', 'resizable=yes,width=1000,height=700,top=0,left=0');
					appWin.opener = window.self;
					//appWin.opener.name = "app_win";
					appWin.focus();
				}
			}

		/*} else {

			//launch the installer
			url = url.replace("?","%3F");
			url = url.replace(/&/g,"%26");
			var pwlh=parent.window.location.href;
			if (pwlh.indexOf("?") > -1) {
				parent.window.location.href=pwlh+'&f=install&callingfn=OpenApp&url='+url;
			} else {
				parent.window.location.href=pwlh+'?f=install&callingfn=OpenApp&url='+url;
			}
		}*/
	}

    function OpenUnreg(url, name) {

		if(user_id=="-1") {

			if (confirm("Only registered SceneCasters can save, write reviews and fully enjoy the experience. Proceed if you just want a taste.")){

			    width = window.screen.width;
			    height = window.screen.height;
			    maxwidth = window.screen.availWidth;
			    maxheight = window.screen.availHeight;

			    if (window.appWin && window.appWin.open && !window.appWin.closed) {
				    window.appWin.focus();
			    }
			    else {
				    appWin = window.open(url, 'app', 'resizable=yes,width=1000,height=700,top=0,left=0');
				    //appWin.opener = window.self;
				    //appWin.opener.name = "app_win";
				    //appWin.focus();
			    }
		    } else{
        	    //return;
			    document.location.href = "step1.php"

			}
        }
	}

	var move;

    function StartMove(direction){
        if(direction=='down') {
            MoveDown();
        } else {
            MoveUp();
        }
    }

    function MoveDown(){
        var instancID = view22RTE.SendAppMessage("GetSelectedObjects","");
        id = instancID.substring(instancID.indexOf(",")+1, instancID.length);
        command = "instanceID="+id+" evalConstraints=false shiftDir=true dir=down amount=1";
        document.view22RTE.SendAppMessage("MoveObject",command);
        move = setTimeout("MoveDown()", 15);
    }

    function MoveUp(){
        var instancID = view22RTE.SendAppMessage("GetSelectedObjects","");
        id = instancID.substring(instancID.indexOf(",")+1, instancID.length);
        command = "instanceID="+id+" evalConstraints=false shiftDir=true dir=up amount=1";
        document.view22RTE.SendAppMessage("MoveObject",command);
        move = setTimeout("MoveUp()", 15);
    }

    function StopMove(){
        clearTimeout(move);
    }
	
	function unloadWindow() {

		if (window.XMLHttpRequest){
			//If IE7, Mozilla, Safari, etc: Use native object
			xmlhttp = new XMLHttpRequest();
		} else {
			if (window.ActiveXObject){
				//If IE6 or IE5
				xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			}
		}

		xmlhttp.open("GET","/web/designer/window_unload.php",true);
		xmlhttp.send(null);
		
		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState==4) {
				//alert("window unloaded");
			}
		}
		
	}

// Help Splash Layers

	/* Functions related to the tip popups and the 'don't show me again' checkbox */
	function createCookie(name,value,days) {
		if (days) {
			var date = new Date();
			date.setTime(date.getTime()+(days*24*60*60*1000));
			var expires = "; expires="+date.toGMTString();
		}
		else var expires = "";
		document.cookie = name+"="+value+expires+"; path=/";
	}

	function readCookie(name) {
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for(var i=0;i < ca.length;i++) {
			var c = ca[i];
			while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
		}
		return null;
	}

	function eraseCookie(name) {
		createCookie(name,"",-1);
	}

	function ShowSplash2d(){
		var c = readCookie("ShowSplash2d");
		if (c==null) {
			createCookie("ShowSplash2d","yes",365);
		}
		c = readCookie("ShowSplash2d");
		if (c=="yes"){
			document.getElementById("Floorplan_help").src="alert_first2d.php";
			document.getElementById("Floorplan_help_layer").style.display="block";
		}
	}

	function HideSplash2d(show_again){
		createCookie("ShowSplash2d",show_again,365);
		document.getElementById("Floorplan_help_layer").style.display="none";
		document.getElementById("Floorplan_help").src="/web/designer/images/spacer.gif";
	}

	function ShowSplash(){
		var c = readCookie("ShowSplash");
		if (c==null) {
			createCookie("ShowSplash","yes",365);
		}
		c = readCookie("ShowSplash");
		if (c=="yes"){
			document.getElementById("Floorplan_help").src="alert_first.html";
			document.getElementById("Floorplan_help_layer").style.display="block";
		}
	}

	function HideSplash(show_again){
		createCookie("ShowSplash",show_again,365);
		document.getElementById("Floorplan_help_layer").style.display="none";
		document.getElementById("Floorplan_help").src="/web/designer/images/spacer.gif";
	}

    function Exit(){
		document.getElementById("Feedback").src="../feedback_beta.php";
		document.getElementById("Feedback_layer").style.display="block";
    }


    function Exit(){
		document.getElementById("alert_exit_layer").style.display="block";
    }

    function ExitConfirm(){
		document.getElementById("alert_exit_layer").style.display="none";
		window.close();

	}

    function ExitCancel(){
		document.getElementById("alert_exit_layer").style.display="none";
    }

	function CloseFeedback() {
		document.getElementById("Feedback").src= "/web/designer/images/spacer.gif";
		document.getElementById("Feedback_layer").style.display="none";
    }

	function Error_NoSceneName() {
		alert("You have not entered a name for this scene.");
    }

	function Error_SceneNameTooLong() {
		alert("Please enter a scene name less than 20 characters.");
    }

	function Exit_NotSaved() {
		alert("You have not saved this scene. Would you like to save it?");
    }

	function Exit_ChangesNotSaved() {
		alert("There are new changes in this scene that have not been saved. Would you like to save those changes?");
    }

	function New_CurrentNotSaved() {
		alert("You have not saved this scene. Would you like to save it before starting a new one?");
    }

	function New_ChangesNotSaved() {
		alert("There are changes in this scene that have not been saved. Would you like to save those changes?");
    }
    
    //returns an array ids of the n selected objects [0 ... n-1]
    //ret[2*n]   = objectId of nth object
    //ret[2*n+1] = instanceId of nth object
    function getSelectedIds()
    {
        var ids = view22RTE.SendAppMessage("GetSelectedObjects","");
        var ret = ids.split(",");
        return ret;
    }
    
    function getSelectedObjectIds()
    {
        ids = getSelectedIds();
        ret = new Array();
        
        for(var i = 0; i < ids.length; i++)
        {
            if(i % 2 == 0)
                ret.push(ids[i]);
        }
        
        return ret;
    }
    
    function getSelectedInstanceIds()
    {
        ids = getSelectedIds();
        ret = new Array();
        
        for(var i = 0; i < ids.length; i++)
        {
            if(i % 2 == 1)
                ret.push(ids[i]);
        }
        return ret;
    }
    
    function populateMissingMetaData()
    {
        var ids = document.view22RTE.SendAppMessage("GetObjects", "");
        ids = ids.split(",");
        
        var object      = [];
        var instance    = [];
        
        for(var i = 0; i < ids.length; i+=2)
        {
            var objectId = parseInt(ids[i]);

            if(ids[i] > 0)
            {
                //make sure instance doesnt have metaData
                if(document.view22RTE.GetMetadata(ids[i+1],"type") == "")
                {
                    //if new type of object then create new object
                    if(instance[objectId] == null)
                    {
                        object[object.length] = objectId;
                        instance[objectId] = ids[i+1];
                    }
                    //if new inst of existing object then just append instance to the instance list
                    else 
                        instance[objectId] = instance[objectId] + "," + ids[i+1];
                }
            }
            else if(ids[i] == -10001)
            {
                //NEED SOLUTION FOR GOOGLE OBJS
            }
        }
        
        for(var i = 0; i < object.length; i++)
            SetInternalMetaData(object[i], instance[object[i]]);
    }   