	var addList = [];						//array of applications to be added
	var removeList = [];					//list of applicationIDs to be removed
	var imageDirectory = "http://ak.imgfarm.com/images/sstb/";
	var flashDirectory = "http://ak.imgfarm.com/images/sstb/flash/";
	var hasChanged=false;					//flag for testing whether a user has changed something about thier toolbar
	var widgetBox = [];						//list of widget Objects for widget page.  Container important properties
	var widgetParam='';						//formatting widget selections for parsing
	var wid="0";							//current widget id
	var widgetQueue=[]; 						//list of widgets that need subscription IDs
	var requestInProgress = false;				//boolean for checking whether all widgets need subscription IDs
	var currentColor="#000;"					//global variable for storing color on custom download page
	var error=false;
	var requestTimer;
	var Modal;				//modal object for easily displaying modals

/******************************************************************************
							Global Functions
*******************************************************************************/
/*Initializes all of the important pieces on the page*/
function init(){       
	Modal = new Modal();
	//stylizes submit/next button
	$("input[type=submit]").each(function(){
		if(this.value=="next"){
			$("input[type=submit]").addClass("stepNav");
			$("input[type=submit]").val("");
			$(".stepNav").wrap("<div class='clearer'></div>");	//IE work around
			$(".stepNav").css("backgroundImage","url("+imageDirectory + "btns/" + themes[LINK_ID].button + ")");
		}
	});
	
	//check for cookies
	if (!navigator.cookieEnabled)
 			alert("We have detected that you have disabled your cookies. \nYou need to enable cookies for this site to function properly!");  		
 		else{	
 			if(!getCookie("SSTBNavigation"))
			setCookie("SSTBNavigation","1[0]&2[]&3[]");	
	}		
	
	//highlight the selected link and category in the navigation
	highlightSelected();
	
	//change all of the important text to match the specified theme colors	
	$(".ThemeColor").each(function(){
		$(this).css("color",THEME_COLOR);
	});

	$(".TopicDesc").append('<a href="javascript: void(0)" class="affinityLink iconLink hints" title="Helpful Hints"></a>');
	iconLinks();  //adds text to links with icons
	printHelpToolTip(LINK_ID);	
	
	//initializes add application links
	$(".addApplicationLink,.AddApplicationLink").click(function(){
		$("a[btnid="+this.getAttribute("btnid")+"].addApplicationLink,a[btnid="+this.getAttribute("btnid")+"].link").each(function(){ changeApplication(this,"add") } );
	});
	
	//initializes remove application links
	$(".removeApplicationLink,.RemoveApplicationLink").click(function(){
		$("a[btnid="+this.getAttribute("btnid")+"].removeApplicationLink,a[btnid="+this.getAttribute("btnid")+"].link").each(function(){ changeApplication(this,"remove") } );
	});
	
	//initiliazes all tooltips
	$('.tooltip').cluetip({width:120, local:true, hideLocal:true, cursor: 'pointer', showTitle: false,cluetipClass: "tooltip",dropShadow: false});
	
	//adds roll over effect to apply changes button
	$("#ApplyChanges").hover(function(){this.style.backgroundPosition = "0 -28px"},
							 function(){ this.style.backgroundPosition = "0 0" }
						);
}
	
function checkWidgetState(){
	if(!requestInProgress && widgetQueue.length==0){
		error=false;
		$("#ApplyChanges,.stepNav").click();
	}
}

/*Un highlights all sprite images, returning them to original state by reseting background-position.*/
	function resetSprites(className){
		var f=0;
		$(className).each(function(){
			$(this).css("backgroundPosition",f+"px 0px");
			f-= parseInt($(this).css("width"));
		});	
	}
	
	/*Iniatializes all of the spites with the given class, setting hover states 
		@spriteClass - string
		@newBGPosition - string for the backgroundPosition representing the hover state
	*/	
	function initSprites(spriteClass,newBGPosition){
		resetSprites(spriteClass);
		
		$(spriteClass).each(function(){
			var bgp = $(this).css("backgroundPosition");
			bgp = bgp.split(" ");
			
			//adding a click event listener
			$(this).click(function(){
				//remove all selected attributes					
				$(spriteClass).each(function(){
					$(this).removeAttr("selected");
				});
				resetSprites(spriteClass);
				
				//highlight only the one that was clicked
				$(this).attr("selected","selected");
				$(this).css("backgroundPosition",bgp[0]+ " " +bgp[1]);

			});

			$(this).hover(function(){
				bgp[1]=newBGPosition;	
				$(this).css("backgroundPosition",bgp[0]+ " " +bgp[1]);
			},
			function(){
				if(!$(this).attr("selected")){
					bgp[1]="0px";
					$(this).css("backgroundPosition",bgp[0]+ " " +bgp[1]);
				}
			});
		});
	}
	
	// display full size banner on pop up window
	function banner(width, height, swf, logourl, title,bannerID){
		title = title.split(",");
		title = "<span class='subheading' style='color:#333'>" + title[0] + "</span> " + "<span style='color:#666' class='subheading'>"+title[1]+"</span>";		
		$("#DialogueTitle").html('<a class="close" href="javascript: void(0)" onclick="tb_remove()"></a>' + title);
		
		//write the swf code into the modal
		var swfCode =  generateSWFCode(swf,width,height,"vicinio_Banner" + bannerID,'',"logoUrl=" + logourl);
		$("#BannerPreview").html( swfCode );
		$("#BannerCode").val( swfCode );	

		tb_display("BannerPreviewModal");

		setTimeout(function(){ ccbtn_ready("vicinioBannerPreview") },800);
		$("#BannerModalContent").find("object,embed").css("visibility","");	

	}
	
	/*takes all nested form fields and moves them to an external form and submits that form via AJAX)*/
	function ajaxsubmit(action,options){
		$("#formReplacement > input").remove();
		$("#formReplacement").attr("action",action);
		
		//move the elements into the external form
		$(".ajaxField").each(function(){
			$(this).clone(true).appendTo("#formReplacement");
		});

		//ajaxify the form 
		if(!options) options={};
        if( $("#formReplacement").ajaxForm(options) ){			
			$("#formReplacement").submit();
		}
	}
	
	/*Initializes text next to links with Icons associated with them*/
	function iconLinks(){
		$(".iconLink").each(function(){
			var clone = $(this).clone(true).appendTo(this);
			var title = this.title;
			title = title.replace(title.charAt(0),title.charAt(0).toUpperCase());
			$(clone).html(title + "<br/>");
			$(clone).removeAttr("class");
			$(clone).addClass("link");
		});
	}
	
	function printHelpToolTip(id){
		var text="";
		if(CATEGORY_ID==0){
			switch (id){
				case 0:
					text = "If you already have an account, make sure you are signed in before beginning work on a new toolbar. If you want to make changes on a previous page, <b>do not use your browser's back button</b>. Use the button provided on the page."
					text+= "<p>If you're uploading a picture for your logo, remember that the image is going to be resized down to 17 pixels high. It'll stay in proportion, but try to choose something that makes sense at that size.</p>";
					break;
				case 1:
					text = "Toolbar topics allow you to add a standard set of features that will appeal to you and your toolbar audience. <p>If you want to mix and match features from different topics, choose the \"none\" option and move on to the next step.</p> <p>Choose as many topics as you want, but remember, you don't want your toolbar to be too crowded. You might still want to add applications, buttons and RSS feeds in upcoming steps!</p>";
					break;
				case 2:
					text = "<p>Didn't see a feature you wanted in the topic groups you chose? You can add it now. Customize your toolbar even further by adding easy one-click access to applications that you and your audience want the most.</p>";
					break;
				case 3:
					text = "You and your audience can have quick access to your favorite or most frequently visited websites. Add buttons by entering website URLs and titles in the spaces provided. Then choose a button style beneath each entry to customize your selections. "
					text +="<p>The button size will be determined by the length of the name you under the URL, so try to keep it short to make the most of your space.<br>You can change the button for your URLs at any time and the change will automatically appear in your toolbar."
					text +="<p>You can add as many buttons as you like by clicking the Add More Buttons button, but remember, the more you add the more crowded your toolbar will become.</p>";
					break;
				/*case 4:
					text = "<p>Your toolbar can keep everyone including you in the loop! An RSS feed is a code that imports content from other websites. So you can have fresh updates from your favorite news sites and blogs on your toolbar.</p>";
					break;*/
				case 4:
					text = "<p>Just a reminder: <b>don't use your browser's back button</b> or else you won't be able to see what progress is being made on your toolbar or whether the process was successful. <p>Take care choosing a name and URL for your toolbar. You can't change them after you've finalized your toolbar. You can, however, change up your features using our editing features after your toolbar has been successfully completed. You can also update your registration information through the Account Maintenance link, which you'll find in the upper right corner of your screen.</p><p>The final step takes a minute because we're processing all of your selected features, so please be patient with us. While you wait, check out some of the things you can do once your toolbar is complete.</p>";
					break;	
			}
		}	
		if(CATEGORY_ID==1){
			switch (id){
				case 0:
					text= "Sending an email will provider your contacts with direct access to download your toolbar. All you need to do is use the tool provided to send them the link to your customized download page." 
					+ "<p>To make it easier, we have provided a tool to import your contacts. All you need to do is select your email provider, enter your credentials, and watch the downloads come in!</p>";
					
				break;
				case 1:
					text = "Your splash page is an online destination where people can download your toolbar. You can choose from a number of background designs and styles. <p>You can also add bullet points that describe your toolbar, so be sure to include information about your toolbar's features. You'll want to entice people to download it, so feel free to be creative!  Customize your font and modify your button style to make the page even more personalized.</p>";
					break;
				case 2:
					text = "Spread the word about your toolbar by creating banner ads that will draw attention!  Select from a number of designs, and then post your ad to any Web page you have, whether it be a blog, social networking profile, or other personal Web site.";
					break;				
			}
		}
		if(CATEGORY_ID==2){
			switch (id){
				case 0:
					text = "Has your toolbar taken off? Find out how many people have downloaded it in a given period of time. Just enter a start and an end date, and our tracker can show your progress. It will also tell you how many people have used your toolbar to search using the MyWebSearch application. All of this information can be graphed on the Tracker page or you can export the data and save it to a spreadsheet on your own computer."
					break;
			}
		}					
		$(".hints").click(function(){   
			Modal.display({type:"hint", title:"Helpful Hints",message:text});
		 });
		
	}
	
	function toolbarSelect(selectElement){
		switch(selectElement.value){
			case "0":
			break;
			
			case "create":
				if(!hasChanged)
					window.location = "createToolbar.jhtml";
			break;
			
			default:
					
				if(!hasChanged){
					var url = window.location.toString().split("?");
					window.location = url[0] + "?t=" + selectElement.value;
				}
				else{
					Modal.display({type: "dialogue", title:"Save changes?", message:"Performing this action will result in you losing all changes made to this page. Are you sure you want to proceed?",confirmText: "Proceed", confirmHandler: function(){ hasChanged=false; toolbarSelect(selectElement) } });
				}
			break;	
			
		}
	}
	
	/*Toggling between different tabs*/									
	function toggle(which){
		$(which).css('display',"none");
		$(which).siblings().css('display',"block");
	}
	
	function login(){
		window.location = "home.jhtml";
	}
	
	/*simple validation of form */
	function validateForm(Form){
		var formValid=true;
		$(Form).find("input[required=true],textarea[required=true").each(function(){
			if(this.value==""){
				formValid=false;
				this.style.backgroundColor="#FFBFC8"
			}
			else{
				this.style.backgroundColor="";
			}
		});
		
		return formValid;
	}
	
				
	
/**************************************************************************************************
								Topic Selection Page
****************************************************************************************************/
function initAffinities(){	
	//removes general tools and featured lists
	$(".affinities").each(function(){
			if($(this).text().toLowerCase().indexOf("general")!= -1 || $(this).text().toLowerCase().indexOf("featured") != -1)
				$(this).remove();			
		});
		
		//replaces spaces in affinity names
		$("p").each(function(){
			var id = $(this).attr("id");
			id=id.replace(/\//g,'').replace(/\s+/g,'');
			$(this).attr("id",id);
		});		
		
		//highlights and unhighlights check boxes when "none" option is selected
		$("input[@type=checkbox]").each(function(){
			var textValue = this.nextSibling.nodeValue.replace(/\//g,'');
			textValue = textValue.replace(/\s+/g,'');
				
			$(this.parentNode).prepend("<img style='float:left; margin-right: 8px' src='" + imageDirectory + "step_03/icons_affinity_" +textValue.toLowerCase() + ".png'/>");
			$(this.parentNode).append("<br/><a class='description link' href='#"+ textValue +"' rel='#" + textValue + "'>Learn More</a>");
			
			if(textValue=="None"){
				$(this).click(function(){
					$("input[@type=checkbox]").attr("checked","")
					this.checked="checked";
					hasChanged = true;
					$("#affinitiessubmit").val(0);
				});
			}
			else{
				$(this).click(function(){
					$("input[@type=checkbox]")[$("input[@type=checkbox]").length-1].checked="";
					hasChanged = true;
					$("#affinitiessubmit").val(1);
				});
			}
		});
				
		$(document).ready(function(){
			$( $(".affinities")[$(".affinities").length-2]  ).remove();
			$('a.description').cluetip({width:300, local:true, cursor: 'pointer', showTitle: false,dropShadow:true,cluetipClass: "tooltip",dropShadow: false});
			
		});
	}

/******************************************************************************
							Affinity Applications Page
*******************************************************************************/
	function checkList(list,value){
		for(var i=0;i<list.length;i++){
			if(list[i]==value){
				list.splice(i,1);
			}
		}
		return list;
	}
	
	function alreadyThere(list,value){
		var isFound=false;
		for(var i=0;i<list.length;i++){
			if(list[i]==value)
				isFound=true;
		}
		
		return isFound;
	}
	
	function changeApplication(button,action){
		var id = button.getAttribute("btnid") || button.getAttribute("id");
		$("a[btnid="+id+"].addApplicationLink,a[btnid="+id+"].removeApplicationLink,a[btnid="+id+"].link").unbind("click");

		if(button.className.indexOf("affinityLink") != -1)
			$(button).removeClass(action+"ApplicationLink");
		
		action = action.toLowerCase();
		
		switch(action){
			//add the application
			case "add":
				if(button.className.indexOf("affinityLink") != -1)
					$(button).addClass("removeApplicationLink");
				
				//tries to find text associated with the button
				try{
					if($(button).find("a")[0].className.indexOf("link") != -1)
						$(button).find("a").text("Remove Application");
				}
				catch(exception){
					if(button.className.indexOf("link")!=-1)
						$(button).text("Remove Application");
				}	
				
				removeList = checkList(removeList,id);
				
				//if the id is already not in the list
				if(!alreadyThere(addList,id))
					addList.push(id);		
				
				//handling widget box subscription IDs	
				if(widgetBox[id]){
					widgetQueue.push(id);
				}
				
				//adds icon to the toolbar
				try{
					if(  $("#toolbar ul").find("li[btnid="+id+"]").length == 0){
						var but = Toolbar.addButton(id,"",apps[id].name,apps[id].icon);
						Toolbar.scrollTo(but);
					}
				}catch(Exception){}
				
				//changes color
				$("a[btnid="+id+"]").parent("td").prev().css("color","#000");
				
				if(button.getAttribute("app")=="widget"){
					if(!document.getElementById("widgetApplications")){
						$("#WidgetApplicationsTitle").after('<div><table border="0" width="100%" id="widgetApplications"></table></div>');
						
						//gets rid of the text "none"
						$(".spanThemesClass").each(function(){
							if($(this).text().indexOf("Applications") != -1 )
								this.nextSibling.nodeValue="";	
						});

					}
					
					if(  $("#widgetApplications").find("a[btnid="+id+"]").length == 0  ){
						
						//adds to the sidenav module
						$("#widgetApplications").append("<tr><td width='7'><img src='http://ak.imgfarm.com/images/sstb/my_toolbar/bullet_blue.png'/></td>"
							+" <td>"+ apps[id].name +"</td>"
							+'<td width="18"><a rel="#MoreDetails" href="#TB_inline?&inlineId=modal&modal=true" btnid="'+id+'" class="affinityLink moreDetails thickbox tooltip" onclick="Modal.display({type: \'Application\', buttonRef: this,title: \'${button.text}\',content: \'${details}\',preview: \'${button.image2}\',applicationID: \''+id+'\', bShowBtns: true})"></a></td>'
							+'<td width="15"><a rel="#RemoveButton" href="javascript:void(0)" btnid="'+ id +'" class="affinityLink removeApplicationLink tooltip"></a></td>');
	
							//adds advent listener to new button
							$("a[btnid="+ id +"]").click(function(){
								$("a[btnid="+ id +"].addApplicationLink,a[btnid="+ id +"].link").each(function(){ changeApplication(this,"remove") } );
							});
					}
				}
				
				if(button.getAttribute("app")=="rss"){
					if(!document.getElementById("widgetRSS")){
						$("#WidgetRSSTitle").after('<div><table border="0" width="100%" id="widgetRSS"></table></div>');
						
						//gets rid of the text "none"
						$(".spanThemesClass").each(function(){
							if($(this).text().indexOf("RSS Feeds") != -1)
								this.nextSibling.nodeValue="";	
						});
					}
					if(  $("#widgetRSS").find("a[btnid="+id+"]").length == 0  ){
					
						//adds to the sidenav module
						$("#widgetRSS").append("<tr><td width='7'><img src='http://ak.imgfarm.com/images/sstb/my_toolbar/bullet_blue.png'/></td>"
							+" <td>"+ apps[id].name +"</td>"
							+'<td width="15"><a rel="#RemoveButton" href="javascript:void(0)" btnid="'+ id +'" class="affinityLink removeApplicationLink tooltip"></a></td>');
	
							//adds advent listener to new button
							$("a[btnid="+ id +"]").click(function(){
								$("a[btnid="+ id +"].addApplicationLink,a[btnid="+ id +"].link").each(function(){ changeApplication(this,"remove") } );
							});
					}
				}
			break;
			
			//remove the application
			case "remove":
				if(button.className.indexOf("affinityLink") != -1)
					$(button).addClass("addApplicationLink");
				
				try{
					if($(button).find("a")[0].className.indexOf("link") != -1)
						$(button).find("a").text("Add Application");
				}
				catch(exception){
					if(button.className.indexOf("link")!=-1)
						$(button).text("Add Application");
				}	
							
				addList = checkList(addList,id);
				
				//if the id is not already in the list			
				if(!alreadyThere(removeList,id))
					removeList.push(id);
					
				try{
					Toolbar.removeButton(id);
				}catch(Exception){}	
				
				$("a[btnid="+id+"]").parent("td").prev().prev().css("color","#999");
				$("a[btnid="+id+"]").parent("td").prev().css("color","#999");
			
				var btns = Toolbar.getButtons();
				Toolbar.scrollTo(btns[btns.length-1],800);
				
			break;
		}
		
		
		//adds click event to new button state
		$("a[btnid="+id+"].addApplicationLink,a[btnid="+id+"].removeApplicationLink").click(function(){
			//changeApplication.call(this,button,"remove");
			$("a[btnid="+id+"].addApplicationLink,a[btnid="+id+"].removeApplicationLink,a[btnid="+id+"].link").each(function(){ 
				if(action=="remove")
					changeApplication(this,"add"); 
				else
					changeApplication(this,"remove"); 
			});
			
		});

		$("#add").val(addList);
		$("#remove").val(removeList);
		hasChanged=true;
	}
	
	/*adds a click event after hte user saves their data*/	
	function initWidgets(){					
			changeTab(1,".AppContainer");
			getSubscriptionIDs();
			//adds a dotted line after evry 3 widgets
			$(".AppContainer").each(function(){
				$(this).find(".widgetBox").each(function(i){
					if((i+1)%3==0)
						$(this).after("<div class='dottedSpacer'></div>");
				});	//end widgetBox 
			});	//end App Container
			
			//prevents form submissions if API calls are still being made
			$("#ApplyChanges,.stepNav").click(function(){
				if(requestInProgress || widgetQueue.length !=0){
					Modal.display({title:"Processing",message:"Please wait a moment while we process your widget selections."});	
					setTimeout("$('#ConfirmButtons').html('<img src=\"http://ak.imgfarm.com/images/sstb/global/progress_bar.gif\"/>')",20);
					getSubscriptionIDs();
					setInterval("checkWidgetState()",1000);
					error=true;
					return false;
				}
				else
					error=false;
			});
			
			 $("#addWidgetLink").click(function(){ 
		 			$('#NewWidgetForm').slideToggle(); 
		 			$('#addWidgetLink').toggleClass("removeApplicationLink");
		 			$('#addWidgetLink').toggleClass("addApplicationLink");
			 });	
	}
	
	/*formats the data into a param string to be processed*/
	function formatWidgetParam(){
		widgetParam = "";
		for(var i=0;i<addList.length;i++){
				var widget = widgetBox[addList[i]];
				if(widget != null)
					widgetParam += widget.appID + "|" + widget.subscriptionID + ",";
			}
			
			widgetParam = widgetParam.substring(0,widgetParam.length-1);
			$("#subids").val(widgetParam);
	}
	
	/*call back function for widgetBox, gets subscription ID*/
	function widgetHandler(responseObj){
		if(responseObj.status=="okay"){
			widgetBox[wid].subscriptionID = responseObj.id;
			formatWidgetParam();
			requestInProgress = false;
			widgetQueue = checkList(widgetQueue,wid);
			clearInterval(requestTimer);
		}else{
			alert("ERROR: " + responseObj.error);
		}
		
	}
	
	/*gets all subscriptions IDs on page load for widgets added from topics*/
	function getSubscriptionIDs(){
		if(!requestInProgress && widgetQueue.length > 0){
			wid = widgetQueue.pop();
			var widget = widgetBox[wid];
			WIDGETBOX.api.installer.subscribe(widget.guid, widget.previewID, 'wbx', 'code', 'IWON', widgetHandler);
			requestInProgress=true;
			requestTimer=setTimeout(function(){   
				requestInProgress=false;
				widgetBox[wid].subscriptionID = widgetBox[wid].previewID;
			 },8000);
		}
		
		setTimeout("getSubscriptionIDs()",1000);
	}
	
	
	function changeTab(which){
		$(".AppContainer").each(function(i){
			$(this).css("display","none");
		
			if(i==which-1)
				$(this).css("display","block");
		});
			
		highlightTab(which);
	}
	
	function highlightTab(which){
		if(arguments[1]){
			//removes "selected" attribute from all tabs
			$(".tab").removeAttr("selected");
			
			$(".tab").each(function(i){
				unhighlightTab(i+1);
			});
			
			$("#tab"+which).attr("selected","selected");
		}
		
		$("#tab"+which).children().css("backgroundPosition","0 -52px");
	}
	
	function unhighlightTab(which){
		if($("#tab"+which).attr("selected") != "selected")
			$("#tab"+which).children().css("backgroundPosition","0 0px");
	}
	
	function changeTab(which,className){
		$(className).each(function(i){
			$(this).css("display","none");
			if(i==which-1)
				$(this).css("display","block");
		});
			
		highlightTab(which,true);
	}

	function processWidget(){
		customWidgets++;
		
		if(validateForm(document.getElementById("NewWidgetForm") )  ){
			var newWidgetString = "";
			$("#NewWidgetForm input[type!=button],textarea").each(function(){ 
				newWidgetString+= this.value + "|"; 
			});
			
			newWidgetString = newWidgetString.replace(/\|$/,'');		//removes the last | at the end
	
			$("#widget1").val(newWidgetString);			
			ajaxsubmit('addCustomWidgets.jhtml',{type:'post',dataType:'xml',success: widgetCallBack});
		}
		else{
			Modal.display({title:"Missing Elements",message:"There are required fields that are missing.  They are highlighted for you in red.  Please provide the necessary information to complete the process."});
		}
			
	 }
	 
	 function widgetCallBack(xml){
	 	try{
		 	var status = xml.getElementsByTagName("status")[0];
		 	var code = status.getAttribute("code");
		 	var msg = status.getAttribute("mesg");
		 	if(code==0 && code !=null){
		 		Modal.display({
		 			type:"dialogue",
		 			title:"Upload Successful", 
		 			message:"Your new widget will be available when the page reloads. Press the reload button or cancel to stay on the page and add more widgets.",
		 			confirmText: "Reload",
		 			confirmHandler: function(){
		 				$(".stepNav, #ApplyChanges").click()
		 			}

		 		});
		 		$("#nWidgets").val(customWidgets);
		 		$("#MainPostForm .stepNav").attr("name","_target"+LINK_ID);
		 		//hides form
	 			$('#NewWidgetForm').slideToggle(); 
				$('#addWidgetLink').toggleClass("removeApplicationLink");
				$('#addWidgetLink').toggleClass("addApplicationLink");

				//clears form
				$('#NewWidgetForm input[type!=button],textarea').each(function(){
					this.value="";
				});
				
				$("#widget1").val('');
		 	}/*else{
		 		Modal.display({title:"An Error Occured", message:"An error occured during the operation.  Your widget was not added. <br/><br/> " + msg});
		 		customWidgets--;
		 	}*/
		 }
		 catch(Exception){
		 	alert("something bad happened\n" + Exception.message);
		 	//Modal.display({title:"An Error Occured", message:"An error occured during the operation.  Your widget may not added successfully. <br/><br/>" + Exception.message});
		 }	
	 	
	 	
	 }

/******************************************************************************
								Custom Buttons
*******************************************************************************/	
function initCustomButtons(){
   //select the icon of the custom button
    $(".affinityBox").each(function(i){
   		var image=$(this).find("#button"+i+"_image").attr("src");
   		
   		if(image && image.indexOf("ak.imgfarm.com") != -1)
			image = image.substr(0,image.length-3);
		else	
			image = image.substr(0,image.length-5);

 		var imageFound = false;
  		$(this).find("input[@type=radio]").each(function(j){
  			if(this.src.indexOf(image)!= -1){
  			   this.checked=true;
  			   imageFound = true;
  			}
  		});
  		
  		if(!imageFound && image.indexOf("spacer")== -1 && image.indexOf("no_button")==-1){
  			insertCustomIcon(this,image+"1.png",true);
  		
  		}
   });
   
   	addEventListeners();
	Toolbar.scrollTo(Toolbar.customButtons[0]);	
	//removes the <script> tag to fix the count of new button forms
	$("#CustomButtonContainer").children("script").remove();
	
	$("#ApplyChanges").unbind("click");
	
	//removes any custom button boxes with default data
	$("#ApplyChanges,.stepNav").click(function(){
		var badURL = false;
		$(".affinityBox").each(function(){
			var parent = this;

			//validates the url and name input boxes
			$(this).find("input[@type=text]").each(function(){
				if(this.value=="Enter URL" || this.value=="Enter button name"  || this.value=="")
					$(parent).remove();
			});
		});
		
		//checking for invalid URLS
		$("input[type=text]").each(function(){
			if(this.getAttribute("valid")=="false"){
				badURL = true;
			 	error=true;
			 }
			 else
			 	error=false;
		});
	
		if(badURL){
			Modal.display({title:"Input Error",message:"Please make sure that all buttons point to valid URLs.  Invalid selections are highlighted in red."});
			return false;
		}
		
		//sets the number of buttons to the number of valid button fields
		$("#nButtons").val($(".affinityBox").length);

		/*if($("#nButtons").val() !=0)
			Toolbar.trackChanges();	//gets the current order.*/
	});
}

//adds event listeners to the custom button input fields for validation and UI
function addEventListeners(){
	$("input[@type=text]").unbind("blur");
	//highlighting the rest of the form on entering of a valid URL
    $("input[@type=text]").blur(function(){
    	var id= $(this).parent().parent().attr("btnid");
    	
    	//if it is the URL box
		if(this.name.indexOf("u") != -1 && this.value != "Enter URL"){
		 	if(Toolbar.changeURL(id,this)){
		 		$(this).parent().siblings(".fadedOut").css("height","0px");
		 		hasChanged=true;
		 	}
		 }	  
 
 		//when button name field is changed
		if(this.name.indexOf("t") != -1 && this.value != "Enter button name"){
			Toolbar.changeButtonName(id,this.value);
			hasChanged=true;
		}
	});	
	
	//highlighting the rest of the form on entering of a valid URL
    $("input[@type=text]").click(function(){   	
    	//if it is the URL box
		if(this.name.indexOf("u") != -1 && this.value == "Enter URL")
		 	this.value="";

 		//do something when button name field is changed
		if(this.name.indexOf("t") != -1 && this.value == "Enter button name")
			this.value="";
		
	});	
	
	//adding event listening for icon radio buttons
   $("input[@type=radio]").click(function(){
   			 var id= "-" + $(this).parent().parent().attr("id");
   			 id=id.substr(id.length-1);
   			 Toolbar.changeButtonIcon("-"+id,$(this).attr("src")); 
   });
   
}

//function that is called to handle generation of an additional field for a new button.
function newButton(buttonID){
	if($(".affinityBox").length < 10){
			var newID= buttonIDs.length+1;
			while(alreadyThere(buttonIDs,newID)){
				newID++;
				newID = newID * -1;
			}
		drawCustomButtons(newID,null,null,null);
		var btn = Toolbar.addButton(-newID, "", "Button" + newID,"");
		//Toolbar.scrollTo(btn);
		buttonIDs.push(newID);
		addEventListeners();
	}

}

//function that will remove all but one button input area
function removeButtonPane(pane){
	if(pane==null){
		var id = $($("#CustomButtonContainer")[0].lastChild).attr("btnid");
			Toolbar.removeButton(id);
			$("#CustomButtonContainer")[0].removeChild($("#CustomButtonContainer")[0].lastChild);
	
		if($("#CustomButtonContainer").children().length == 0)
			$("#removeButton")[0].disabled="disabled";
	}
	else{
		var id = pane.attr("btnid");
		$("a[btnid="+id+"]").parent("td").parent().fadeOut("fast");
		pane.fadeOut("normal",function(){
			Toolbar.removeButton(id);
			$(this).remove();

			buttonIDs = checkList(buttonIDs,this.id);
		});
	}
}

/************************************************************************************
							Custom Web Page Scripts
***************************************************************************************/
function savePage(){
		paramString="";
		var c=1;
		for(i in stylesObj){
			paramString+= i + "=" + eval("stylesObj."+i+".text");
			
			var formatted="";
			for(s in stylesObj[i].styles)
				formatted+=s + ":"+ stylesObj[i].styles[s]+";";
				
			paramString+="|"+ "style"+c+ "=" + toCSS(formatted) + "|";
			c++;
		}
		
		paramString+="layoutid=" + layoutID + "|buttonid="+ buttonID;
		document.forms["MainPostForm"].paramString.value = paramString;
		document.forms["MainPostForm"].templateId.value = 1;
		document.forms["MainPostForm"].submit();
	}
	
	function changeText(id,str){
		eval("stylesObj."+id+".text= escape(str.replace(/(<([^>]+)>)/ig,'')); ");
		$(window.frames[0].document.getElementById(id)).text(str);
		hasChanged=true;
	}
	
	/*toggles styles on and off*/
	function changeStyles(element,id,style){
		var ref = eval("stylesObj."+id+".styles");
		
		switch(style){
			case 'fontWeight':
				if(ref.fontWeight=='normal'){
					ref.fontWeight='bold';
					toggleButton(element,"on");
				}
				else{
					ref.fontWeight="normal";
					toggleButton(element,"off");
				}
			break;
			
			case 'fontStyle':
				if(ref.fontStyle=='normal'){
					ref.fontStyle='italic';
					toggleButton(element,"on");
				}
				else{
					ref.fontStyle="normal";
					toggleButton(element,"off");
				}
			break;
			
			case 'textDecoration':
				if(ref.textDecoration=='none'){
					ref.textDecoration='underline';
					toggleButton(element,"on");
				}
				else{
					ref.textDecoration="none";
					toggleButton(element,"off");
				}
			break;
			
			case 'fontFamily':
				ref.fontFamily = element.value;
			break;
			
			case 'color':
				ref.color = element;
			break;
		}
		
		$(window.frames[0].document.getElementById(id)).css(eval("stylesObj."+id+".styles"));
		hasChanged=true;
	}
	
	function changeButton(element,buttonNum){
		hasChanged=true;
		buttonID=buttonNum;
		window.frames[0].document.getElementById('clickHere').style.backgroundImage = element.style.backgroundImage;
	}
	
	/*broke out the function responsible for highlighting the bold/italics/underline buttons*/
	function toggleButton(button,state){
		if(state=="on")
			$(button).css("background-position","left bottom");
		else
			$(button).css("background-position","left top");
		
		hasChanged=true;
	}
	
	function changeFontsize(option,ui){
		$(window.frames[0].document.getElementById("paragraph"+(slider+1))).css("fontSize",ui.value);
		 eval("stylesObj.paragraph"+(slider+1)+".styles.fontSize=ui.value+'px'");
		 hasChanged=true;
		
	}	

	function newWin(state){
		switch(state){
			case "open":
			//get the dimensions of the screen
			var winW = 1024;
			var winH = 860;
			 if (!$.browser.msie) {
			 	
			 	if(window.innerWidth > 1024)
				 	winW = window.innerWidth;
				 	
				 winH = window.innerHeight;
			 }
			 else{
			 	if(document.body.offsetWidth > 1024)
				  	winW = document.body.offsetWidth;
				  
				winH = document.body.offsetHeight;
			 }
				var callback = function(){
					$(window.frames[0].document.body).prepend("<div id='optionbar' style='display: none'></div>");
					$(window.frames[0].document.getElementById("container")).prepend('<a href="#" id="cancel" onclick="window.parent.newWin();"></a><a href="#" id="save" onclick="window.parent.savePage()"></a>');
					$(window.frames[0].document.getElementById("optionbar")).slideDown("normal");
					
					setTimeout(function(){
						$(window.frames[0].document.getElementById("cancel")).css("visibility","visible");
						$(window.frames[0].document.getElementById("save")).css("visibility","visible");
					},400);
					
				}
				
				if(($.browser.msie) && parseInt($.browser.version) < 7){
					//if IE6 or lower
					$("iframe").css("position", "absolute");
					$("iframe").animate({width: 1024, height: winH * .95, left: winW * .05, top: winH * .01},300,callback);
				}
				else{
					$("iframe").animate({width: 1024, height:  winH*.95, left: -250, top: -240},300,callback);
				}
					
			window.frames[0].document.getElementById("content").style.top="";
			break;

			default:
				$(window.frames[0].document.getElementById("cancel")).remove();
				$(window.frames[0].document.getElementById("save")).remove();
				$(window.frames[0].document.getElementById("optionbar")).remove();
				
				//if IE 6
				if(($.browser.msie) && parseInt($.browser.version) < 7)
					$("iframe").css({width: '473px', height: '361px', left: '0px', top: '0px',position: "relative"});
				else	//if a good browser
					$("iframe").animate({width: 473, height: 361, left: 0, top: 0},300);
				
				window.frames[0].document.getElementById("content").style.top="0";
			break;
		}
	}
	
	function changeTheme(templateID,element){
		var css = imageDirectory + "css/splash/sstb_" + templateID + ".css";
		
		if($.browser.msie && $.browser.version <= 6){		
			setTimeout(function(){
				window.frames[0].document.getElementsByTagName("link")[1].href = css;	
			},1000);
		}
		else
			window.frames[0].document.getElementsByTagName("link")[1].href = css;
		
		
		if(element){
			layoutID=templateID;
			$("#options .affinityLink").removeClass("removeLink");
			$("#options .affinityLink").addClass("addLink");
			if(element.className.indexOf("link") == -1){
				$(element).removeClass("addLink");
				$(element).addClass("removeLink");
			}
		}

		hasChanged=true;
	}
	
	function initGUI(id,styles){
		var inc = parseInt( id.charAt(id.search(/\d/g)) );
		var sty;
		if(styles=="" || styles=="undefined") 
			styles="font-weight:normal;text-decoration:none;font-style:normal;font-size:12pt;font-family:arial;color:#000;";
					
		sty = unserialize(toJS(styles));
		//initialize all elements in the GUI based on settings

		
		var container = document.getElementById("font"+inc).parentNode;
       	$("#font"+inc).find("option").each(function(i){
       		if(this.value == sty.fontFamily)
       			this.selected=true;
       	});
       	
 		
       	//initialize all elements in the GUI based on settings
       	$(container).find(".button").each(function(){
       		if(this.className.indexOf("bold") != -1 && sty.fontWeight == "bold")
       			toggleButton(this,"on");
       			
       		if(this.className.indexOf("underline") != -1 && sty.textDecoration == "underline")
       			toggleButton(this,"on");
       			
       		if(this.className.indexOf("italic") != -1 && sty.fontStyle == "italic")
       			toggleButton(this,"on");
       	});
       	
       	
       	var startVal=12;
		eval("stylesObj."+id+"={ text: escape($('#"+id+"Text').val()),styles: sty}");
		startVal = parseInt(sty.fontSize);

		//font slider won't initialize in gecko browsers AFTER page loads
		if(!$.browser.msie)
			$($(".fontSlider")[inc-1]).slider({min:9,startValue:startVal,max:58,slide:changeFontsize});
		

		$(document).ready(function(){
			if($.browser.msie)	//IE needs to init the slider after the page loads
				$($(".fontSlider")[inc-1]).slider({min:9,startValue:startVal,max:58,slide:changeFontsize});
			

			//initialize color pickers
			$("#"+id+"Color").ColorPicker({
				parentID: id + "Color",
				onShow: function (colpkr) {
					$("#"+id+"Color").parent().css("position","relative");
					$(colpkr).fadeIn(200);
					$(colpkr).css({left: "0px", top: "0px"});
					
					//hide form elements in IE6 or lower
					if($.browser.msie && $.browser.version < 7){					
						$("#options").find("select").each(function(i){
							if(i > inc-1)
								$(this).css("visibility","hidden");
						});
					}	
				},
				onHide: function (colpkr) {
					$(colpkr).fadeOut(200,function(){ 
						$("#"+id+"Color").parent().css("position","static");
					});
					if(currentColor)
						changeStyles("#"+currentColor,currentID,"color");
					
					if($.browser.msie && $.browser.version < 7)
						$("#options").find("select").css("visibility","visible");
					
						
					return false;
				},
				onChange: function (hsb, hex, rgb) {
					$("#"+id+"Color > div").css('backgroundColor', '#' + hex);
					currentColor=hex;
				},
				color: eval("stylesObj."+id+".styles.color")
			});
		});
		
		$("#"+id+"Color > div").css('backgroundColor',eval("stylesObj."+id+".styles.color"));
	}
	
	//turns a CSS string into an object
	function unserialize(stylesList){
		stylesList = stylesList.substring(0,stylesList.length-1);
		var styles = stylesList.split(";");
		var style_obj={};		
		
		for(var i=0;i<styles.length;i++){
			var s = styles[i].split(":");
			eval("style_obj." + s[0]+"= s[1]");
		}
		
		return style_obj;
	}
	
	//turns a JS formatted CSS string back into CSS
	function toCSS(string){
		var str = string;
		while(str.search(/[A-Z]/) != -1){
			var s = str.search(/[A-Z]/);
			var c = str.charAt(s);
			c = "-" + c.toLowerCase();
			str = str.replace(str.charAt(s),c);
		}

		return str.toLowerCase();
	}
	
	//turns a CSS formated CSS string into JS
	function toJS(string){
		var str = string;
		while(str.search("-") != -1){
			var s = str.search("-");
			var c = str.charAt(s+1);
			str = str.replace("-","");
			var str = str.substr(0,s) + c.toUpperCase() + str.substr(s+1);
		}	

		return str;
	}
	
	function scrollTo(ElementID){
		var offset=$(window.frames[0].document.getElementById(ElementID)).offset();
		$(window.frames[0].document.documentElement).animate({scrollTop: offset.top,scrollLeft: offset.left},1000);			
		return offset;
	}
	
	function setColor(){
		try{
			$("#"+currentID + "Color").find("div").css("backgroundColor","#"+currentColor);
		}catch(e){ alert(e.message)}
	}

/***************************************************************************************************************************
												Registration Page 
***************************************************************************************************************************/	
function ValidRadioButton(){	
	if (document.getElementById("tosYes").checked)
		error=false;
	else{
		Modal.display({type:"alert", title: "Notice", message: "Please agree with the <strong>Terms of Service</strong> before you can complete your toolbar", confirmText: "Ok"});
		error=true;
	}
	
	return error;
}

function ValidSpace(elementID){
	var fieldName = "";
	if (elementID ==  "toolbar.name")
		fieldName = "Toolbar Name";
	else
		fieldName = "Download Page";
	
	if (document.getElementById(elementID).value == ""){
		Modal.display({title:"Notice", message:"<strong>"+ fieldName +"</strong> can not be empty. Please fill it in before proceed.", confirmText:"Ok"});
		error=true;
		return;
	}
	else
		error=false;

	if (elementID != "toolbar.name")
	{
		var pos = document.getElementById(elementID).value.indexOf(" ");
		
		if (pos > -1){
			Modal.display({title:"Notice", message: "Please make sure there is no space in the <strong>"+ fieldName +"</strong>", confirmText: "Ok"});
			error=true;
		}else
			error=false;
	}
}

/***************************************************************************************************************************
												Partner Edit Page
***************************************************************************************************************************/	
function ToggleInputFields(state){
	switch(state){	
		case "off":
			$("input[type=text],input[type=password], textarea").css({border: "0px solid #FFF",color: "#999",backgroundColor: "#FFF" });
			$("input, textarea").attr("disabled","disabled");
			document.getElementById("submitBtn").style.display = "none";	
		break;
		
		case "on":
			$("input[type=text],input[type=password], textarea").css({border: "1px solid #AAA",color: "#000",backgroundColor: "#FFF" });
			$("input, textarea").removeAttr("disabled");
			document.getElementById("submitBtn").style.display = "block";
		break;
	}
}

/**************************************************************************************************************
										Banners Page
*****************************************************************************************************************/
var bannerID=0;
function drawSwfBanner(swf, titleText, bannerType,logo){
	var height;
	var width;
	var dimensions;
	var title = [];
	
	switch(bannerType){
		case 1: //med rectangle
			title[0] = "Medium Rectangle Ad";
			height = 133;
			width = 160;
			dimensions = "300x250".split("x");
		break;
		
		case 2: //small rect
			title[0] = "Small Rectangle Ad";
			width = 126;
			height = 105;
			dimensions = "180x150".split("x");
		break;
		
		case 3: //leaderboard
			title[0] = "Skyscraper Ad";
			width = 87;
			height = 325;
		
			dimensions = "160x600".split("x");
			
		break;
		
		case 4: //skyscraper
			title[0] = "Leaderboard Ad";
			width = 340;
			height = 42;
			dimensions = "728x90".split("x");
		break;
	}
	
	title[1] = titleText;
	
	//putting it all together
	var embedCodeSpan = "<span id='AdBannerPreview"+bannerID+"'>" 
	+ generateSWFCode(swf,width,height,"vicinio_Banner" + bannerID,'',"logoUrl=" + logo)
	+ "<span class='PopUpIconSpan'><a href='javascript: void(0)' title='Preview Banner' class='PopUpIconA' onclick=\"banner("+dimensions[0]+","+ dimensions[1] + ",'" + swf +"', '"+logo+"', '"+ title+"', "+bannerID + ")\" ></a></span> <br/>"
	+ '<object height="23" width="97" wmode="transparent" allowscriptaccess="always" flashvars="ready=ccbtn_ready&amp;id=Banner'+bannerID+'&amp;urchin=ckTrk" data="' + flashDirectory + 'copyCode.swf" type="application/x-shockwave-flash" id="Banner' + bannerID + '" style="margin-top: 6px">'
    + '<param name="movie" value="' + flashDirectory + 'copyCode.swf" />'
    + '<param name="allowscriptaccess" value="always" />'
    + '<param name="flashvars" value="ready=ccbtn_ready&amp;id=Banner'+ bannerID + '&amp;urchin=ckTrk" />'
    + '<param name="wmode" value="transparent"/>'
    +'</object>'
    + "<input type='hidden' name='embedcode' value='" + generateSWFCode(swf,dimensions[0],dimensions[1],"vicinio_Banner" + bannerID,'',"logoUrl="+logo) +  "' /></span>";
	 	
	document.write("<td>" + embedCodeSpan + "</td>");		//printing it to the page.
	
	bannerID++;
}	
/*Blank Click tracking function for copycode */
function ckTrk(){}


/*Ready function for copy code functionality*/
function ccbtn_ready(id){		
  try{
       document.getElementById( id ).setClipboardData(  $("#" + id).siblings("input").val()  );
  }
  catch(e)
  {} //will try again in .5 seconds		
}

function generateSWFCode(url,width,height,id,className,flashVars,version){
	if(!flashVars){flashVars='';}
	if(!version){version='8,0,0,0';}
	if(!id){ id=''}
	if(!className){ className=''}
	
	var embedCode = '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version='+version+'" align="middle"'
	+ 'height="'+height+'" width="'+width + '" id="'+id + '">'
	+	'<param name="allowScriptAccess" value="always" />'
	+	'<param name="movie" value="' + flashDirectory + 'banners/'+url+'"/>'
	+   '<param name="wmode" value="transparent" />'
	+	'<param name="quality" value="high" />'
	+	'<param name="FlashVars" value="'+flashVars+'">'
	+	'<embed src="' + flashDirectory + 'banners/'+url+'" quality="high" allowScriptAccess="always" align="middle"'
	+	' FlashVars="' + flashVars + '"'
	+	' wmode="transparent" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" height="'+height+'" width="'+width+'"/>'
	+ '</object>';
	
	return embedCode;
}
/*Modal Object for easily displaying Modals
	@options = object of configurable parameters
   {
   		title (string): 			Title of the modal (defaults to: "Alert")
   		message(string):			"Message to display" 
   		confirmText(string):		"Confirm button text"
   		confirmHandler(function):	what to do after the user hits the confirm buton
   		type(string):				The type of modal to display (alert || dialogue || hint || upload || application || iframe)
   }
*/
function Modal(){ return this; }
Modal.prototype = {
	init: function(){/*Sets up elements inside the modal depending on the type passed in.  This makes it easier to change the content inside a modal*/
		$("#modal").css("display","block");
		var HTML="";
		var type= this.options.type.toLowerCase();
		switch(type){
			case "hint":
			case "dialogue":
			case "alert":
			case "upload":
				 HTML+= '<h2 id="DialogueTitle"><a class="close" href="javascript: void(0)" onclick="tb_remove()"></a></h2>'
				 +'<h3 id="DialogueMessage"></h3>';
			
				 if(type=="dialogue" || type=="alert" || type=="upload"){
					 HTML +='<span id="ConfirmButtons" class="clearer" style="position: relative; left: 15%; margin-top: 30px;">'
					 + '<a href="javascript:void(0)" id="DialogueConfirm" class="confirm" style="color:#FFF">Ok</a>';
				 }
				 
				 if(type=="dialogue" || type=="upload")
				 	 HTML+= '<a href="javascript:void(0)" class="cancel" onclick="tb_remove()">Cancel</a>';
				 
				 if(type=="dialogue" || type=="alert" || type=="upload"){
				 	HTML+="</span>";
 				}
			break;
			
			case "application":
			$("#modal").css("display","block");

			HTML+='<div class="RSS_category"><a class="close" href="javascript: void(0)" onclick="tb_remove()"></a>'
			+ 'Add Application: <span id="ApplicationTitle"></span>' 			
			+ '</div><div class="FeedContent">'
			+ '<table><tr>'
			+ '<td valign="top"><iframe id="AppPreview" ></iframe>'
	  		+	'</td><td valign="top" width="245"><div id="AppDesc"></div>'
			+ 		'<div id="modalButtons">'
			+ 			'<a href="javascript:void(0)" id="DialogueConfirm" class="confirm" style="color:#FFF">Add Application</a>'
			+			'<a href="javascript:void(0)" class="cancel" onclick="tb_remove()">Cancel</a>'
			+		'</div></td></tr></table></div>';
			break;
		}
		
		 				
		$("#ModalContent").html(HTML + "</form>");	
	},
	
	//for displaying widgets
	application: function(){	
		var options = this.options;
		$("#modalButtons").css({position: "absolute", bottom: "50px"});
		//sets up modal with information about application
		//sets the title of the widget
		$("#ApplicationTitle").text(options.title);
		
		//resizes the iframe 
		if(widgetBox[options.applicationID]){
			var widget = widgetBox[options.applicationID];
	
			document.getElementById("AppPreview").src = imageDirectory + "/widgets/displayWidget.html?appId="+widget.previewID;
			
			if($.browser.msie && parseInt($.browser.version) >=6){
				setTimeout(function(){
					window.frames["AppPreview"].window.location.refresh();
				},800);
			}
			
			$("#AppPreview").css({height:  '340px',width: '450px'});
			
			if(widget.height > 340)
			$("#AppPreview").css({height: widget.height+10 + 'px'});
			
			if(widget.width > 330)
				$("#AppPreview").css({width: widget.width+10 + 'px'});
		}
		else{	//add the preview image
			var img = new Image();
			img.src = options.preview;
			
			try{
				$("#AppPreview").css({height: img.height-50, width: img.width-50});
				document.getElementById("AppPreview").src = options.preview;
			}
			catch(exception){
				document.getElementById("AppPreview").src = options.preview;
			}
		}
	
		//sets the description of the widget
		$("#AppDesc").text(unescape(options.content));
		
		$(".confirm").attr("id",options.applicationID);
		$(".confirm").click(function(){
			changeApplication($(options.buttonRef.parentNode).siblings("a")[0],"add");
			tb_remove();
		});
		
		//do not show buttons when a user clicks from navigation module
		if(options.hideButtons)
			$("#modalButtons")[0].style.display = 'none';
		else
			$("#modalButtons")[0].style.display = '';

	},
	
	dialogue: function(){
		$("#ConfirmButtons").css("left","15%");
		
		$("#DialogueTitle").html('<a class="close" " href="javascript: void(0)" onclick="tb_remove()"></a>' + this.options.title);
		$("#DialogueMessage").html(this.options.message);
		$("#DialogueConfirm").text(this.options.confirmText);
		$("#DialogueConfirm").unbind();
		if(this.options.confirmHandler!=null)
			$("#DialogueConfirm").click(this.options.confirmHandler);
		else
			$("#DialogueConfirm").click(tb_remove);	
	},
	
	alert: function(){
		this.dialogue();
		$("#ConfirmButtons").css("left","25%");
	},
		
	hint: function(){
		this.dialogue();
	},
	
	upload: function(){
		//sets upload specific variables
		var options = this.options;
		this.options.message = "Select a file from your computer to upload. <br/><br/>"+
		"<input type='file' name='Filedata' class='ajaxField'/>" + 
		"<div class='error'></div><br/>"+
		"<input type='checkbox' name='legal' id='legal'/><span class='note'>"+
		"By uploading a file you certify that you have the right to distribute this picture and that it does not violate the <a href='termsofservice.jhtml' target='_blank'>Terms of Service.</a></span>";
		
		
		if(options.imgType=="icon")
			this.options.message+= "<input type='hidden' name='type' value='icon'><br/><br/> Please note your images will be resized to 17x17 pixels.";
			
		this.options.confirmText = "Upload";
		this.dialogue();
		
		$("#DialogueConfirm").unbind();
		
		//upload file validation
		$("#DialogueConfirm").click(function(){
			//check to see if there is a file to upload
			if (document.forms["tempForm"].Filedata.value == ''){
				$(".error").text("Please select a file to upload");
				return;
			}	
			
			//check to see if the checkbox has been checked
			if(!document.forms["tempForm"].legal.checked){
				$(".error").text("Please certify that you can legally use this image.");
				return;
			}
			
			$(".error").text("");

			 $("#tempForm").attr("action","/selfserve/upload.jhtml");
			 if($("#tempForm").ajaxForm({success: options.confirmHandler, dataType: 'xml'}))
				$("#tempForm").submit();
				
			m_bUploadFromFileBrowser = true;
		});
			
	},	
	
	display: function(options){
		if(options==null) options = {};
		if(options.type==null) options.type="alert"
		if(options.title==null) options.title="Alert!";
		if(options.message==null) options.message="";
		if(options.confirmText==null) options.confirmText="Ok";
		this.options = options;

		this.init();
		eval("this." + this.options.type.toLowerCase() + "()");
		
		if(options.type != "application")
			tb_display("modal",null,450);

		
	}
}