// JavaScript Document
var genezoomon = true;
var tooltipdepth = 10000;
var tooltipholder = null;
var tooltipdefault = "Click to view details";
var newwin;
var allheadlines = new Array();
var headlinecount = 0;
var bannerTime = 7000; //7 seconds
var bannerInterval;
var activeSubNav;
var prevInput;
var mouseyOffset;

var checkProspectEmailTimeout;

var pl = new Array(); // array to store video playlist
var plbrowse = 6; // default number of thumbs to load
var firstplbrowse = 12; // number of thumbs to load playlist on first call
var plcurrentpage = 1; // current page of playlist
var plnextpage = 1; // next page number of playlist
var plsort = "ra"; // deafult sort for playlist (mv = most viewed, mp = most popular, ra = recently added, al = alphabetical)
var pltotal;
var plcount = 0;
var plwidth = 738; // visible playlist width
var scrollswitch = false; //switch to enable/disable playlist navigation
var currentvideo = 0;
var plopp = "";
var plcat = "";
var plvideo = "";
var plsearch = "";
var plnetwork = "";
var pluser = "";
var videoplaying = "";
var autoclick = false;

var orgswitch = false;
var contactfocus = false;

var mytimeout1;
var mytimeout2;

var spottype = ""; // type of SPOT selected
var spotsize = ""; // size of SPOT selected
var spottheme = ""; // theme of SPOT selected
var spotfile = ""; // file of SPOT selected
var spotInfo = "";
var xOffset = 100;
var yOffset = 0;
var mouseOffset = 250;
var timeSpan = 100;

var helpID;
var arID;

;(function(h){h.fn.addOption=function(){var j=function(a,f,c,g){var d=document.createElement("option");d.value=f,d.text=c;var b=a.options;var e=b.length;if(!a.cache){a.cache={};for(var i=0;i<e;i++){a.cache[b[i].value]=i}}if(typeof a.cache[f]=="undefined")a.cache[f]=e;a.options[a.cache[f]]=d;if(g){d.selected=true}};var k=arguments;if(k.length==0)return this;var l=true;var m=false;var n,o,p;if(typeof(k[0])=="object"){m=true;n=k[0]}if(k.length>=2){if(typeof(k[1])=="boolean")l=k[1];else if(typeof(k[2])=="boolean")l=k[2];if(!m){o=k[0];p=k[1]}}this.each(function(){if(this.nodeName.toLowerCase()!="select")return;if(m){for(var a in n){j(this,a,n[a],l)}}else{j(this,o,p,l)}});return this};h.fn.ajaxAddOption=function(c,g,d,b,e){if(typeof(c)!="string")return this;if(typeof(g)!="object")g={};if(typeof(d)!="boolean")d=true;this.each(function(){var f=this;h.getJSON(c,g,function(a){h(f).addOption(a,d);if(typeof b=="function"){if(typeof e=="object"){b.apply(f,e)}else{b.call(f)}}})});return this};h.fn.removeOption=function(){var d=arguments;if(d.length==0)return this;var b=typeof(d[0]);var e,i;if(b=="string"||b=="object"||b=="function"){e=d[0];if(e.constructor==Array){var j=e.length;for(var k=0;k<j;k++){this.removeOption(e[k],d[1])}return this}}else if(b=="number")i=d[0];else return this;this.each(function(){if(this.nodeName.toLowerCase()!="select")return;if(this.cache)this.cache=null;var a=false;var f=this.options;if(!!e){var c=f.length;for(var g=c-1;g>=0;g--){if(e.constructor==RegExp){if(f[g].value.match(e)){a=true}}else if(f[g].value==e){a=true}if(a&&d[1]===true)a=f[g].selected;if(a){f[g]=null}a=false}}else{if(d[1]===true){a=f[i].selected}else{a=true}if(a){this.remove(i)}}});return this};h.fn.sortOptions=function(e){var i=h(this).selectedValues();var j=typeof(e)=="undefined"?true:!!e;this.each(function(){if(this.nodeName.toLowerCase()!="select")return;var c=this.options;var g=c.length;var d=[];for(var b=0;b<g;b++){d[b]={v:c[b].value,t:c[b].text}}d.sort(function(a,f){o1t=a.t.toLowerCase(),o2t=f.t.toLowerCase();if(o1t==o2t)return 0;if(j){return o1t<o2t?-1:1}else{return o1t>o2t?-1:1}});for(var b=0;b<g;b++){c[b].text=d[b].t;c[b].value=d[b].v}}).selectOptions(i,true);return this};h.fn.selectOptions=function(g,d){var b=g;var e=typeof(g);if(e=="object"&&b.constructor==Array){var i=this;h.each(b,function(){i.selectOptions(this,d)})};var j=d||false;if(e!="string"&&e!="function"&&e!="object")return this;this.each(function(){if(this.nodeName.toLowerCase()!="select")return this;var a=this.options;var f=a.length;for(var c=0;c<f;c++){if(b.constructor==RegExp){if(a[c].value.match(b)){a[c].selected=true}else if(j){a[c].selected=false}}else{if(a[c].value==b){a[c].selected=true}else if(j){a[c].selected=false}}}});return this};h.fn.copyOptions=function(g,d){var b=d||"selected";if(h(g).size()==0)return this;this.each(function(){if(this.nodeName.toLowerCase()!="select")return this;var a=this.options;var f=a.length;for(var c=0;c<f;c++){if(b=="all"||(b=="selected"&&a[c].selected)){h(g).addOption(a[c].value,a[c].text)}}});return this};h.fn.containsOption=function(g,d){var b=false;var e=g;var i=typeof(e);var j=typeof(d);if(i!="string"&&i!="function"&&i!="object")return j=="function"?this:b;this.each(function(){if(this.nodeName.toLowerCase()!="select")return this;if(b&&j!="function")return false;var a=this.options;var f=a.length;for(var c=0;c<f;c++){if(e.constructor==RegExp){if(a[c].value.match(e)){b=true;if(j=="function")d.call(a[c],c)}}else{if(a[c].value==e){b=true;if(j=="function")d.call(a[c],c)}}}});return j=="function"?this:b};h.fn.selectedValues=function(){var a=[];this.selectedOptions().each(function(){a[a.length]=this.value});return a};h.fn.selectedTexts=function(){var a=[];this.selectedOptions().each(function(){a[a.length]=this.text});return a};h.fn.selectedOptions=function(){return this.find("option:selected")}})(jQuery);

function hideSubNav() {
				$(".ic_catlnk").hide();$("#subnav").hide();
							//$('embed,object').show();
				if($('#topnav').css('float')!='none') {
					$(activeSubNav).show();$("#subnav").show();
				}
}

function makeButtons(where) {
if(typeof(where) == "undefined")
	var where = '';
$(where+' .button, button').not(".non_standard_btn").each(function(){
		var b = $(this);
		var tt = b.html() || b.val();
		b.html('').css({cursor:'pointer'}).html('<i></i><span>' + tt + '<i></i><span></span></span>');
		//alert(b.html());
	});	
}

function checkLanguages() {
$('#gsn_web_profile .language_select').each(function () {									  
					$(this).parents('p.language_p').css('position','').css('left','');
					$(this).removeClass('noneselected');
					if($(this).selectedTexts()[0]=='None') {
						$(this).addClass('noneselected');		
					}
 });
														  
$('#gsn_web_profile .noneselected:gt(0)').parents('p.language_p').css('position','absolute').css('left','-5000px');
}
this.imagePreview = function(){
 /* CONFIG */



 // these 2 variable determine popup's distance from the cursor
 // you might want to adjust to get the right result

 /* END CONFIG */
 $(".hover_preview").hover(function(e){
 if(e.pageX > 0)
		 mouseOffset = e.pageX;
 if(e.pageY > 0)
		 mouseyOffset = e.pageY;
 //if($(this).attr("rel")=='potd') {
 //xOffset = -535;
 //yOffset = -350;
 //} else {
 //xOffset = -235;
 //yOffset = -50;
 //}
 
 //var c = (this.title != "") ? "<br/>" + this.title : "";
 $("body").append("<p id='preview_spot_hover' style='position:fixed; top:-600px; left:1000px;'><img src='"+ $(this).attr('rel') +"' /></p>");
  setTimeout(' rePositionPreview('+e.pageX+');',200);
 },
 function(){
// this.title = this.t;
 $("#preview_spot_hover").remove();
 });
 $(".hover_preview").mousemove(function(e){
  rePositionPreview(e.pageX,e.pageY);
 });
	
}; 
 function rePositionPreview(epagex,epagey) {
	 if($('#preview_spot_hover img').height() < 50) {
			setTimeout('rePositionPreview(0);',200);
			return;
	 }
	 yOffset = Math.round($('#preview_spot_hover img').height()/2)*-1;
	 if(epagex > 0)
		 mouseOffset = epagex;
 	 if(epagey > 0)
		 mouseyOffset = epagey;
	 if(yOffset<-10) {
		 
		 try {
			var yyy = parent.$('window');
			newTopPosition = (($(window).height()/2) + yOffset);
		 } catch(e) {
			newTopPosition = (mouseyOffset + yOffset); 
		 }
		 if(newTopPosition < 0) {
			newTopPosition = 0; 
		 }
	  $("#preview_spot_hover")
 .css("position","fixed").stop().animate({ 
        top: newTopPosition + "px",
        left: (mouseOffset + xOffset) + "px"
      }, Math.round( Math.abs($("#preview_spot_hover").css('left').replace('px','') - (mouseOffset + xOffset))/2) );
	 } else {
		  setTimeout('rePositionPreview(0);',200); 
	 }
 }
 
 function checkProspectEmail(delayvar) {
								clearTimeout(checkProspectEmailTimeout);
								checkProspectEmailTimeout = setTimeout("$.get('/my/remote/username_exists?fv_username='+$('#prospect_contact input[name=fv_email]').val(),function (data) {																	if(data.indexOf('none') != -1 || data.indexOf($('#contact_id_h1').attr('rel'))!=-1) {																																$('#prospect_contact input[name=fv_email]').css('background-color','');																		$('#prospect_contact form').unbind('submit');																		} else {																			$('#prospect_contact input[name=fv_email]').css('background-color','pink');																			$('#prospect_contact form').unbind('submit');																			$('#prospect_contact form').submit(function () {																														 alert('There is already a contact in your database with this email address. Please change the email address of this contact to save this form.');																														 return false;																														   });																		} 																   });",delayvar);
								
																   }
																   
function checkNewContactEmail(delayvar) {
								clearTimeout(checkProspectEmailTimeout);
								checkProspectEmailTimeout = setTimeout("$.get('/my/remote/username_exists?fv_username='+$('#buildprospect input[name=fv_email]').val(),function (data) {		if(data.indexOf('none') != -1 && checkEmailVal($('#buildprospect input[name=fv_email]').val())) {																																$('#buildprospect input[name=fv_email]').css('background-color','');																		$('#addprospect form').unbind('submit'); } else if(checkEmailVal($('#buildprospect input[name=fv_email]').val())==false) { $('#buildprospect input[name=fv_email]').css('background-color','pink');																			$('#addprospect form').unbind('submit'); $('#addprospect form').submit(function () {																														 alert('Please enter a valid email address.');																														 return false;																														   });  } else { $('#buildprospect input[name=fv_email]').css('background-color','pink');																			$('#addprospect form').unbind('submit');$('#addprospect form').submit(function () {																														 alert('There is already a contact in your database with this email address. Please change the email address of this contact.');																														 return false;																														   });																		} 																   });",delayvar);
								
																   }
 
$(function(){
	// ******************* Init Scripts Start Here ************************************
	
	
	//This code changes the ThickBox Pop-Up Title to match the first H1, h2, or legend found in the iframed page.
	//If it can't find those it resorts to the Title field.
	//If there isn't a title it resorts to the original rel title.
	try {
	  var newAjaxTitle = $('h1:first,h2:first,legend:first').eq(0).text();
	  if(newAjaxTitle.length == 0)
	  	newAjaxTitle = $('title').eq(0).text();
	  if(newAjaxTitle.length != 0)
		parent.$('#TB_ajaxWindowTitle').text(newAjaxTitle);

	} catch(e) {
	var crashed_changing_title = e;	
	//alert(e);
	}

	
	/******** Admin Tab Forms ********/
	$('#prospect_contact input[name=fv_email]').keypress(function () { checkProspectEmail(750); });
	
	$('#gsn_web_role_access input[name=fv_inactive_flag]').each(function () {
																		  if($(this).val() == '0') {
																			  $(this).css('background-color','lightgreen');
																		  } else {
																		     $(this).css('background-color','pink'); 
																		  }
																		  });
	$('#gsn_web_role_access input[name=fv_inactive_flag]').click(function () {
																		  if($(this).val() == '0') {
																			  $(this).val('1').css('background-color','pink');
																		  } else {
																		      $(this).val('0').css('background-color','lightgreen');
																		  }
																		  $(this).blur();
																		   });
	
	$('#calendar_sync_button').click(function () { $('#sync_options').show(); });
	$('textarea').each( function () {
								  if($(this).attr('maxlength')>0) {
										$(this).keypress(function () {
														if($(this).val().length>$(this).attr('maxlength')) {
															$(this).val($(this).val().substr(0,$(this).attr('maxlength')));
															return false;
														}
																   });
								  }
								  });
	
	imagePreview();
	$('#start_and_end_times .date_field_end').click(function () {
										
										$(this).children().each( function () {
   											 var startdate = eval($('#start_and_end_times .date_field_start').val().replace(':','').replace('12','').replace('am','').replace('pm','+1200'));
											
											 if(eval($(this).val().replace(':','').replace('12','').replace('am','').replace('pm','+1200'))<startdate) {
												$(this).attr('disabled','disabled');
											 } else {
												 $(this).removeAttr('disabled');
											 }
											 
											
										  });
										timeSpan = eval($('#start_and_end_times .date_field_end').val().replace(':30',':50').replace(':','').replace('12','').replace('am','').replace('pm','+1200')) - eval($('#start_and_end_times .date_field_start').val().replace(':30',':50').replace(':','').replace('12','').replace('am','').replace('pm','+1200'));
										
										
										});
	$('#start_and_end_times .date_field_start').click(function () {
										/* $(this).children().each( function () {
   											 var enddate = eval($('#JT_copy .date_field_end').val().replace(':','').replace('12','').replace('am','').replace('pm','+1200'));
											 if(eval($(this).val().replace(':','').replace('12','').replace('am','').replace('pm','+1200'))>enddate) {
												
												$(this).attr('disabled','disabled');
											 } else {
												 $(this).removeAttr('disabled');
											 }
											 
										  });*/
										 
										// if(!timeChanged) {
										 	
											var newEndTime = eval(($(this).val().replace(':30',':50').replace(':','').replace('12','').replace('am','').replace('pm','+1200')));
											//alert(newEndTime);
											//alert(timeSpan);
											newEndTime = newEndTime + timeSpan;
											//alert(newEndTime);
											var newEndTimeHour = Math.floor(newEndTime / 100);
											//alert(newEndTimeHour);
											 var newEndTimeMinute = (newEndTime - (newEndTimeHour * 100)) / 100 * 60;
											 //alert(newEndTimeMinute);
											if(Number(newEndTimeHour)-12 == 0)
											    newEndTime = '12:'+newEndTimeMinute+'pm';
											else if(Number(newEndTimeHour)-12 > 0) {
												if(Number(newEndTimeHour)-24 >= 0)
													newEndTime = '11:30pm';
												else
													newEndTime = (newEndTimeHour - 12) + ':'+newEndTimeMinute+'pm';
											} else
												newEndTime = (newEndTimeHour) + ':'+newEndTimeMinute+'am';
											$('#start_and_end_times .date_field_end').selectOptions(newEndTime.replace('0pm','00pm').replace('0am','00am').replace('300','30'));
											//alert(newEndTime.replace('0pm','00pm').replace('0am','00am').replace('300','30'));
										// }
										 });
	
	
	$('input.noedit, select.noedit').click(function () {
													$('input.noedit, select.noedit').removeClass('noedit'); 
													 });
	$('input[name=fv_phone]').each(function () {
											 
											 $(this).val(getFormattedPhoneNumber($(this).val()));
										
											 if($(this).val().substr(0,2)!='+1' && $(this).val().replace(/[^0-9]/g, '').length < 13) {
																												$('#us_warn_number').show();
																												
																											 } else {
																												$('#us_warn_number').hide(); 
																											 }
											 
											 }).blur(function () {
																											 $(this).val(getFormattedPhoneNumber($(this).val()));
																											 if($(this).val().substr(0,2)!='+1' && $(this).val().replace(/[^0-9]/g, '').length < 13) {
																												$('#us_warn_number').show();
																												
																											 } else {
																												$('#us_warn_number').hide(); 
																											 }
																										   } );
	//checkLanguages();
	/*$('#gsn_web_profile .language_select').change(function () {
					checkLanguages();
					
															});*/
	// Get environment path from URL
  	urlString = window.location.pathname;
	endSlashPos = urlString.lastIndexOf("/");
  	urlString = urlString.substring(5,endSlashPos);
	if (((urlString == "ngstest") || (urlString == "ngsdemo")) && (window.name != "myaccount")) {
		$("body").prepend("<div id='ips_testflag'>Test System</div>");
	} else if ((urlString == "ngsdev") && (window.name != "myaccount")) {
		$("body").prepend("<div id='ips_testflag'>Development System</div>");
	}
	
	makeButtons();
	/*
	//Fix buttons
	$("a.button, button").append("<span></span>");/*each(function() {
		var btn_contents = "<span>" + $(this).html() + "</span>";
		$(this).html(btn_contents);
		});*/
	
	// ******************* Init Scripts End Here *************************************
 $('#template_box .template_choice').click(function () {	var answer = confirm('Overwrite email subject and body?');	if (answer){ $('#template_box div').removeClass('selected');																																		$('input[name=fv_subject]').val($('#subject'+$(this).attr('id').substr(1)).val()); setContent($('#body'+$(this).attr('id').substr(1)).val()); $(this).addClass('selected'); $('#template_box #template_id').val($(this).attr('id').substr(1)); } });  if($('#template_box #template_id').length >0  && $('#template_box #template_id').val() >= 0) {  $('#template_box div').removeClass('selected'); $('#t'+$('#template_box #template_id').val()).addClass('selected'); }
	
	// ******************* Graphical Genealogy Scripts Start Here ***********************
	/*$(".genemain td a").mouseover(function() {tooltipholder = $(this).attr("title"); $(this).attr("title", tooltipdefault);});
	$(".genemain td a").mouseout(function() {$(this).attr("title", tooltipholder); tooltipholder = null;});
	
	$(".genemain td a").click(function() {	
			var myhref = this.href;
			var mytitle = ($(this).attr("title") == tooltipdefault) ? tooltipholder : $(this).attr("title");
			var myname = mytitle.substring(0, mytitle.indexOf("<BR>"));
			myname = myname.substring(myname.indexOf(":")+1);
			$(this).parent().append("<div class='tooltip'><div class='toolhead'><span>" + myname + "</span><a href='#' class='toolminimize'>-</a>&nbsp;&nbsp;<a href='#' class='toolclose'>X</a></div><div class='toolbody'></div><div class='toolfooter'><a href='" + myhref + "'>View this member's genealogy</a></div></div>");
			mytitle = mytitle.substring(mytitle.indexOf("<BR>")+4);
			mytitle = mytitle.replace(/:/g, ":</label>");
			mytitle = mytitle.replace(/<BR>/g, "</p><p><label>");
			mytitle = "<p><label>" + mytitle;
			$(this).parent().find(".tooltip div.toolbody").html(mytitle);
			
			$(this).removeAttr("title");
			
			var offset = {};
			$(this).offset({ scroll: false }, offset);
			$(this).parent().find(".tooltip").css(offset).each(function() {adjustPosition(this, 20, 35); tooltipdepth++; this.style.zIndex = tooltipdepth;}).click(function() {tooltipdepth++; this.style.zIndex = tooltipdepth;});	
			
			$(this).parent().find(".tooltip a.toolclose").click(function() {
				$(this).parent().parent().remove();
				return false;
			});
			
			$(this).parent().find(".tooltip a.toolminimize").toggle(function() {
				$(this).parent().parent().find(".toolbody, .toolfooter").hide();
			}, function () {
				$(this).parent().parent().find(".toolbody, .toolfooter").show();
			});
			
			$(this).parent().find(".tooltip").show();
			return false;
		});*/	
	// ******************* Graphical Genealogy Scripts End Here ***********************

	// ******************* Scrolling Banner Scripts Start Here ************************
	$("#banner").each(function() {
		$.get("gsn_web_banner.startup",
		 	function(xml){
 		 	$("headline",xml).each(function() {
				tempheadline = $(this).text();
				allheadlines.push(tempheadline);				//alert(txt);
				});			
		 	setupBanner();
		 	});
		});

	// ******************* Scrolling Banner Scripts End Here ************************
	
	
	// ******************* Org and Lang Selection Scripts Start Here ************************
	$("#myorg").click(function() {
		$("#langlist").hide();
		$("#orglist").load("/gsnapi/orglist", function() { 
			$(this).show(); 
			$("#orglist a.listclose").click(function() { $(this).parent().hide(); }); 
		});
	});
	
	$("#mylang").click(function() {
		$("#orglist").hide();
		$("#langlist").load("/gsnapi/langlist", function() {	
			$(this).show(); 
			$("#langlist a.listclose").click(function() { $(this).parent().hide(); }); 
		});
	});
	
	// ******************* Org and Lang Selection Scripts End Here ************************
	
	
	// ******************* Navigation Scripts Start Here ************************
	//Show active subnav
	$('#subnav').hide();
	$("#topnav li a").each(function() {
		var tabClass = $(this).parent().attr("class");
		if (tabClass) {
			if (tabClass.indexOf("tabactive") != -1 ) {
				var tabID = $(this).parent().attr("id");
				var subnavID = activeSubNav = "#sub_" + tabID;
				if($('#topnav').css('float')!='none') {
					$(subnavID).show();$('#subnav').show();
				}
			}
		}
	});
	//Show subnav for another topnav
	var subnav_hider = setTimeout('',100);
	
	$("#topnav li a").mouseover(function() {
		$(".ic_catlnk").hide();
		var tabID = $(this).parent().attr("id");
		var subnavID = "#sub_" + tabID;
		if($('#topnav').css('float')=='none') {
				$('#JT').remove();	
		}
		if($(subnavID).length < 1)
			$('#subnav').hide();
		else
			$('#subnav').show();
		clearTimeout(subnav_hider);
		$(subnavID).show().mouseover(function() {
			clearTimeout(subnav_hider);
			/*$(".ic_catlnk").hide();
			$(this).show();*/
		}).mouseout(function() {
			clearTimeout(subnav_hider);
			//Isagenix Vertical Menu, shorter timeout for subnav disappear
			if($('#topnav').css('float')=='none')
				subnav_hider = setTimeout('hideSubNav();',1000);
			else
				subnav_hider = setTimeout('hideSubNav();',1000);

		});
		//Isagenix - Vertical Menu System
		if($('#topnav').css('float')=='none')
			$('#subnav').css('left',$(this).parents('li').position().left);
			//if(jQuery.browser.msie)
				//$('embed, object').hide();
	}).mouseout(function() {
			clearTimeout(subnav_hider);
			//Isagenix Vertical Menu, shorter timeout for subnav disappear
			if($('#topnav').css('float')=='none')
				subnav_hider = setTimeout('hideSubNav();',1000);
			else
				subnav_hider = setTimeout('hideSubNav();',1000);
	});
	
	$("#openupgrade").click(function() { $("#prospectsummaryupgrade").show("fast");});
	$("#closeupgrade").click(function() { $("#prospectsummaryupgrade").hide("fast");});
	
	$("#activity_report #rpt_close").click(function() { self.parent.tb_remove(); return false; });
	
	// ******************* Navigation Scripts End Here ************************
	
	
	// ******************* Cust Reg Scripts Start Here ************************
	
	$(".matrix_feature a").click(function() {
		$(this).parent().find("p").slideToggle("fast");
		var toggleImg = $(this).find("img").attr("src");
		if (toggleImg == "/images/ver2_images/bullet_toggle_plus.gif") {
			$(this).find("img").attr("src", "/images/ver2_images/bullet_toggle_minus.gif");
		} else {
			$(this).find("img").attr("src", "/images/ver2_images/bullet_toggle_plus.gif");
		}
		return false;
	});
	
	$("#gsn_web_registration #EMAIL").focus();
	
 	$("#expand_all_matrix").click(function () {    
   		$(".matrix_feature p").slideDown("fast");
		$(".matrix_feature a img").attr("src", "/images/ver2_images/bullet_toggle_minus.gif");
    	return false;
 	}); 
	
 	$("#collapse_all_matrix").click(function () { 
  		$(".matrix_feature p").slideUp("fast");
		$(".matrix_feature a img").attr("src", "/images/ver2_images/bullet_toggle_plus.gif");
  		return false;
 	}); 
	
	// check product radio buttons and if checked, show star packages if necessary and populate order summary with appropriate product
	$("#regprods input").each(function() {
		var prodID = this.value;
		var prodIDID = $(this).attr("id");
		var parentdiv = $(this).parent().parent().parent().parent().parent().parent().parent().parent().attr("id");
		if (this.checked == true) {
			prevInput = this;
			// if radio button is tied to either three star or 5 star packages then show div containing that package
			if (parentdiv != "gsn_web_account") {
				if (prodIDID == '3STAR' || prodID == '2') {
					$("#3star_package").show("normal");
				}
				if (prodIDID == '5STAR' || prodID == '3') {
					$("#5star_package").show("normal");
				}
			}
			
			// loop through products array and populate order summary with data from appropriate row
			for (i=0; i<prods.length;i++) {
				if (prods[i][0] == prodID)	{
					$("#prodpackage .price").html("$"+ prods[i][2] +"/mo");
					$("#prodpackage .desc").html(prods[i][3]);
					if (document.location.href != "http://us.repstars.com/my/registration/thanks") {
						$("#prodpackagedesc .desc").html(prods[i][4]);
					}
				} 
			}
		}
	});
	
	$(".add_package input").each(function() {
		var prodID = this.value;
		if (this.checked == true) {
			// loop through products array and populate order summary with data from appropriate row
			for (i=0; i<prods.length;i++) {
				if (prods[i][0] == prodID)	{
					//alert("array works --> " + prods[i]);
					$("#starpackage .price").html("$"+ prods[i][2]);
					$("#starpackage .desc").html(prods[i][3]);
					$("#starpackagedesc .desc").html(prods[i][4]);
				} 
			}
			$("#PROMO_CODE").val("");
			$("#PROMO_FORM").hide();
		}
	});
	
	$("#fv_setup_coupon").each(function() {
		var couponcode = $(this).val();
		if (couponcode != "") {
			for (i=0; i<coups.length;i++) {
				if (coups[i][0] == couponcode)	{
					if(couponcode.substr(0,7) == 'CB30DAY') {
						$("#setupcoupon .desc").html("Full Discount for Entry Level Service");
					} else {
						$("#setupcoupon .desc").html("Coupon Code: " + coups[i][0]);
					}
                    if (coups[i][1]=="") {
						$("#setupcoupon .desc").append(" - " + coups[i][2] + "% OFF");
						var prodPrice = $("#setupfee .price").text();
						prodPrice = prodPrice.substring(1);
						var couponDiscount = prodPrice * (coups[i][2] * .01);						
						$("#setupcoupon .price").html("-$" + couponDiscount.toFixed(2));
                    }
                    else {
						var couponDiscount = coups[i][1]*1;		
						$("#setupcoupon .price").html("-$" + couponDiscount.toFixed(2));
                    }
					if (document.location.href != "http://us.repstars.com/my/registration/thanks") {
						var removeHTML = '<br /><a href="#" onclick="removeSetupCoup();">Remove Coupon</a>';
						$("#setupcoupon .desc").append(removeHTML);
					}
					$("#setupcoupon").show();
				} 
			}
		}
	});
	
	
	$("#fv_prod_coupon").each(function() {
		var couponcode = $(this).val();
		updateProdCoupon(couponcode);
	});
	
	
	$("#regprods input").mousedown(function() {
		var prodCoupon = $("#fv_prod_coupon").val();
		var changeCoup = true;	
		for (i=0; i<coups.length;i++) {
			//alert(prodCoupon);
			if (coups[i][0] == prodCoupon)	{
				if (coups[i][3] == "") {
					changeCoup = false;
				} 
			} 
		}
		if ((prodCoupon != "") && (changeCoup)) {
			var changeProd = confirm("You have previously selected a package that has a coupon applied to it. Changing this package will remove the coupon as well. Do you want to continue changing your selection?");
		} else {
			var changeProd = true;
		}
		if (changeProd) {
			prevInput = this;
			var prodID = this.value;
		        var prodIDID = $(this).attr("id");
			for (i=0; i<prods.length;i++) {
				if (prods[i][0] == prodID)	{
					//alert("array works --> " + prods[i]);
					$("#prodpackage .price").html("$"+ prods[i][2] +"/mo");
					$("#prodpackage .desc").html(prods[i][3]);
					if (document.location.href != "http://us.repstars.com/my/registration/thanks") {
						$("#prodpackagedesc .desc").html(prods[i][4]);
					}
				} 
			}
			
			if (changeCoup) {
				$("#prodpackagecoupon .desc").html("");
				$("#prodpackagecoupon .price").html("");
				$("#prodpackagecoupon").hide();
				$("#fv_prod_coupon").val("");
				$("#starpackage .price").html("");
                            	$("#starpackage .desc").html("");
                            	$("#starpackagedesc .desc").html("");
                            	$("#starpackage").hide();
                            	$("#starpackagedesc").hide();
                                $("#PROMO_FORM").show();
			} else {
				updateProdCoupon(prodCoupon);
			}
			
			$(".add_package input").removeAttr("checked");
			$(".add_package").hide();
			var parentdiv = $(this).parent().parent().parent().parent().parent().parent().parent().parent().attr("id");

			if (parentdiv != "gsn_web_account") {
				if (prodIDID == '3STAR' || prodID == '2') {
					$("#3star_package").show("normal");
				}
				if (prodIDID == '5STAR' || prodID == '3') {
					$("#5star_package").show("normal");
				}
			}
			this.checked = true;
			
			calculateOrderTotal();
			
		} else {
			prevInput.checked = true;
			return false;
		}
	});
	
	$(".add_package input").click(function() {
		if (this.checked == true) {
                        $("#setupcoupon .desc").html("");
                        $("#setupcoupon .price").html("");
                        $("#setupcoupon").hide();
                        $("#fv_setup_coupon").val("");

			var prodID = this.value;
			for (i=0; i<prods.length;i++) {
				if (prods[i][0] == prodID)	{
					//alert("array works --> " + prods[i]);
					$("#starpackage .price").html("$"+ prods[i][2]);
					$("#starpackage .desc").html(prods[i][3]);
					$("#starpackagedesc .desc").html(prods[i][4]);
					var couponcode = prods[i][1];
				} 
			}
			for (i=0; i<coups.length;i++) {
				if (coups[i][0] == couponcode)	{
					//alert("array works --> " + prods[i]);
					if(couponcode.substr(0,7) == 'CB30DAY') {
						$("#prodpackagecoupon .desc").html("Full Discount for Entry Level Service");
					} else {
						$("#prodpackagecoupon .desc").html("Coupon Code: " + coups[i][0]);
					}
                    if (coups[i][1]=="") {
						$("#prodpackagecoupon .desc").append(" - " + coups[i][2] + "% OFF");
						var prodPrice = $("#prodpackage .price").text();
						prodPrice = prodPrice.substring(1);						
						var moPos = prodPrice.indexOf("/mo");
						prodPrice = prodPrice.substring(0,moPos);
						//alert(prodPrice);
						
						var couponDiscount = prodPrice * (coups[i][2] * .01);
						$("#prodpackagecoupon .price").html("-$" + couponDiscount.toFixed(2) + "/mo");
                    }
                    else {
						var couponDiscount = coups[i][1]*1;
						$("#prodpackagecoupon .price").html("-$" + couponDiscount.toFixed(2) + "/mo");
                    }
					if (document.location.href != "http://us.repstars.com/my/registration/thanks") {
						var removeHTML = '<br /><a href="#" onclick="removeProdCoup();">Remove Coupon</a>';
						$("#prodpackagecoupon .desc").append(removeHTML);
					}
					$("#prodpackagecoupon").show();
					$("#fv_prod_coupon").val(coups[i][0]);
				} 
			}
                        $("#PROMO_CODE").val("");
                        $("#PROMO_FORM").hide();
			$("#starpackage").show();
			$("#starpackagedesc").show();
		} else {
			$("#starpackage .price").html("");
			$("#starpackage .desc").html("");
			$("#starpackagedesc .desc").html("");
			$("#starpackage").hide();
			$("#starpackagedesc").hide();
			$("#fv_prod_coupon").val("");
			$("#prodpackagecoupon .desc").html("");
			$("#prodpackagecoupon .price").html("");
			$("#prodpackagecoupon").hide();
                        $("#PROMO_FORM").show();
		}
		
		calculateOrderTotal();
	});
	// ******************* Cust Reg Scripts End Here ************************
	
	
	// ******************* Help Scripts Start Here ************************
	$("#help a").click(function() {
		helpID = "#text_" + this.id;
		
		if($('#help p:visible').length != 0 && $('#help p:visible').attr("id") != $(helpID).attr("id"))
			$('#help p:visible').slideUp("fast",function() { $(helpID).slideToggle("fast"); });
		else
			$(helpID).slideToggle("fast"); 
		
		
		$(this).toggleClass("helpexpanded");
	});
	
	$(".expand_text_area").focus(function() { $(this).height("200px"); }).blur(function() { $(this).height("16px"); });
	
	$(".expand_opp").click(function () {
		$(this).parent().parent().find(".opp_more_info").slideToggle();	
		return false;
	});
	// ******************* Help Scripts End Here ************************
	
	
	// *********************Build Prospect List Scripts Start Here ******************
	$("#add_manual_btn").click(function() {
		$("#buildprospect div#uploadcsv").hide();	
		$("#buildprospect div#addprospect").slideToggle("fast");
		return false;
	});
	
	$("#upload_csv_btn").click(function() {
		$("#buildprospect div#addprospect").hide();
		$("#buildprospect div#uploadcsv").slideToggle("fast");
		return false;
	});
	// *********************Build Prospect List Scripts End Here ******************
	
	// *********************Media Playlist Scripts Start Here ******************

	$("#media_playlist #videothumbs").each(function () {
		var querystring = document.location.search;
		querystring = querystring.substring(1);
		searchparams = querystring.split("&");
		for (i=0; i<searchparams.length;i++) {
			var searchname = searchparams[i].substring(0,11);
			/*if (searchname == "O") {
				plopp = searchparams[i].substring(2);
				//alert("opp="+plopp);
			} else if (searchname == "C") {
				plcat = searchparams[i].substring(2);
				//alert("cat="+plcat);
			} else if (searchname == "V") {
				plvideo = searchparams[i].substring(2);
				//alert("video="+plvideo);
			} else if (searchname == "S") {
				plsort = searchparams[i].substring(2);
				//alert("sort="+plsort);
			} else */if (searchname == "fn_group_id") {
				plnetwork = searchparams[i].substring(12);
				//alert("network="+plnetwork);
			} /*else if (searchname == "U") {
				pluser = searchparams[i].substring(2);
				//alert("user="+pluser);
			}*/				
		}
		getVideoThumbs(plcurrentpage, firstplbrowse, plsort, plsearch, plopp, plcat, plvideo, plnetwork, pluser, true);
		scrollswitch = true;
	});
	$("#media_playlist #nextvideo a").click(function () {
		// alert(plcurrentpage + " --> " + plnextpage); 
		if (scrollswitch) {
			if (plcurrentpage < plnextpage) {
				scrollswitch = false;
				var newleft = $("#media_playlist #videothumbs ul").css("margin-left");
				newleft = newleft.replace(/px/, "");
				newleft -= plwidth; 
				//alert(newleft);
				$("#media_playlist #videothumbs ul").animate({
  					marginLeft: newleft
					}, 1000, function () { scrollswitch = true; });
				plcurrentpage++;
				getVideoThumbs(plcurrentpage + 1, plbrowse, plsort, plsearch, plopp, plcat, plvideo, plnetwork, pluser);
			}
		}
		return false;
	});
	
	$("#media_playlist #prevvideo a").click(function () {
		if (scrollswitch) {
			if (plcurrentpage > 1) {
				scrollswitch = false;
				var newleft = $("#media_playlist #videothumbs ul").css("margin-left");
				newleft = newleft.replace(/px/, "");
				newleft = (newleft* 1) + plwidth;
				//alert(newleft);
				$("#media_playlist #videothumbs ul").animate({
  					marginLeft: newleft
					}, 1000, function () { scrollswitch = true; });
				plcurrentpage--;
			}
		}
		return false;
	});
	
	$("#sortlist a").click(function () {
		if (scrollswitch) {
			var selsort = this.href;
			var hashindex = selsort.indexOf("#");
			selsort = selsort.substring(hashindex+1);
		
			if (plsort != selsort) {
				plsort = selsort;
				pl.length = 0; // clear array
				plcurrentpage = 1; // reset current page back
				plnextpage = 1; // reset next page
				plcount = 0; // reset playlist count
				var currheight = $("#media_playlist #videothumbs ul").height() + "px";
				$("#media_playlist #videothumbs ul").width(plwidth*2).css("margin-left", 0).empty();
				getVideoThumbs(plcurrentpage, firstplbrowse, plsort, plsearch, plopp, plcat, plvideo, plnetwork, pluser);	
			}
		}		
		return false;
	});
	
	
	$("#videosearch #videotags").keypress(function(e) {
		if (e.which == "13") {
			$("#videosearch button").click();
		}
	});
	$("#videosearch button").click(function() {
		if (scrollswitch) {
			plsearch = $("#videosearch #videotags").val();		
			if (plsearch != "") {
				pl.length = 0; // clear array
				plcurrentpage = 1; // reset current page back
				plnextpage = 1; // reset next page
				plcount = 0; // reset playlist count
				plopp = ""; // reset browse by opportunity
				plcat = ""; //reset browse by category
				plvideo = ""; //reset video loaded
				plnetwork = ""; //reeset network group
				pluser = ""; //reset user
				$("#media_playlist #videothumbs ul").width(plwidth*2).css("margin-left", 0).empty();
				getVideoThumbs(plcurrentpage, firstplbrowse, plsort, plsearch, plopp, plcat, plvideo, plnetwork, pluser);	
			}
		}		
		return false;						
	});
	
	/*$("#media_details .searchtag").click(function() {
			var searchtag = $(this).text();
			$("#videosearch #videotags").val(searchtag);
			$("#videosearch button").click();
			return false;
		});*/
	
	$("#media_details .searchtag").click(function() {
		if (scrollswitch) {
			plsearch = $(this).text();			
			$("#all_playlists h1#current span").text(label_pl_current_1 + " '" + plsearch + "'");
			pl.length = 0; // clear array
			plcurrentpage = 1; // reset current page back
			plnextpage = 1; // reset next page
			plcount = 0; // reset playlist count
			plopp = ""; // reset browse by opportunity
			plcat = ""; //reset browse by category
			plvideo = videoplaying; //video currently loaded
			plnetwork = ""; //reeset network group
			pluser = ""; //reser user
			currentvideo = 0;
			//alert("video id="+plvideo);
			$("#media_playlist #videothumbs ul").width(plwidth*2).css("margin-left", 0).empty();
			getVideoThumbs(plcurrentpage, firstplbrowse, plsort, plsearch, plopp, plcat, plvideo, plnetwork, pluser, true);	
		}		
		return false;						
	});
	
	$("#media_by a").click(function() {
		if (scrollswitch) {
			pluser = $(this).text();	
			//$("#all_playlists h1#current span").text(label_pl_current_2 + " '" + pluser + "'");
			pl.length = 0; // clear array
			plcurrentpage = 1; // reset current page back
			plnextpage = 1; // reset next page
			plcount = 0; // reset playlist count
			plopp = ""; // reset browse by opportunity
			plcat = ""; //reset browse by category
			plvideo = ""; //reset video loaded
			plnetwork = ""; //reeset network group
			plsearch = ""; //reser search keywords
			$("#media_playlist #videothumbs ul").width(plwidth*2).css("margin-left", 0).empty();
			getVideoThumbs(plcurrentpage, firstplbrowse, plsort, plsearch, plopp, plcat, plvideo, plnetwork, pluser, true);	
		}		
		return false;						
	});
	// *********************Media Playlist Scripts End Here ******************

	// *********************SPOT Configure Scripts Start Here ******************
	$("#xsmallopt").attr("disabled","disabled");
	//$("#video_spot_options").hide();
	
	$("#spot_form #type").change(function() { 
		if (this.value == "1") { 
			$("#video_spot_options").show(); 
		} else { 
			$("#video_spot_options").hide(); 
		} 
		try {
		if ((this.value == "1") && (($("#spot_form #size").val() == "1") || ($("#spot_form #size").val() == "3"))) {
			$("#custom_text_options").hide();
		} else {
			$("#custom_text_options").show();
		}
		} catch(e) {
			$("#custom_text_options").hide(); 	
		}
		if(this.value == "1") {
			$("#xsmallopt").removeAttr("disabled");
		} else if(this.value =="2") {
			try {
			if($("#spot_form #size").val() == "3") {
				$("#spot_form #size").selectOptions("1",true).change();		
			}
			} catch (e) {
				var zsszz = zsszz;
			}
			$("#xsmallopt").attr("disabled","disabled");
		} else {
			$("#xsmallopt").attr("disabled","disabled");
		}
		spottype = this.value; 
		getpreviewSWF(); 
	});
	$("#spot_form #type").change();
	
	$("#spot_form #size").change(function() { 
		if (this.value == "2") { 
			$("#small_spot_options").show(); 
		} else { 
			$("#small_spot_options").hide(); 
		} 					
		try {
		if (((this.value == "1") || (this.value == "3")) && ($("#spot_form #type").val() == "1")) {
			$("#custom_text_options").hide(); 
		} else {
			$("#custom_text_options").show(); 
		}
		} catch(e) {
			$("#custom_text_options").show();
		}
		/*if(this.value == "3") {
			$("#spot_form #theme option").attr("disabled","disabled");	
			$('#whitegreentheme').removeAttr("disabled");
			$("#spot_form #theme").selectOptions("2",true).change();
		} else {
			$("#spot_form #theme option").removeAttr("disabled");
		}*/
		spotsize = this.value; 
		getpreviewSWF(); 
	});
	$("#spot_form #size").change();
	$("#spot_form #theme").change(function() { spottheme = this.value; getpreviewSWF(); });
	$("#spot_form #theme").change();
	$("#spot_form input[name='fv_message'], #spot_form input[name='fv_button_text'], #spot_form input[name='fn_contact_info'], #spot_form input[name='fn_share_media_id']").change(function() { getpreviewSWF(); });
	
	$(".spot_share").each(function() {
		var tempURL = $(this).attr("rel");
		var tempfileloc = tempURL.indexOf("?s=");
		var tempfile = tempURL.substring(0,tempfileloc);
		var tempspotid = tempURL.substring(tempfileloc+3);
		//alert(tempfile);
		/*switch (tempfile) {
		case "/archive/spot/spot_video.swf":
  			swfwidth = '332';
			swfheight = '490';
 			break;
		case "/archive/spot/spot_video_sm.swf":
  			swfwidth = '252';
			swfheight = '373';
 			break;
		case "/archive/spot/spot_prospect.swf":
  			swfwidth = '332';
			swfheight = '290';
 			break;
		case "/archive/spot/spot_prospect_sm.swf":
  			swfwidth = '252';
			swfheight = '253';
 			break;
		case "/archive/spot/spot_call.swf":
  			swfwidth = '332';
			swfheight = '190';
 			break;
		case "/archive/spot/spot_call_sm.swf":
  			swfwidth = '252';
			swfheight = '178';
 			break;
		}
				
		var embedHTML = '<embed src="http://us.repstars.com';
		embedHTML += tempURL + '"';
		embedHTML += ' width="' + swfwidth + '" height="' + swfheight + '"';
		embedHTML += ' allowfullscreen="true" wmode="transparent" type="application/x-shockwave-flash"></embed>';
		
		$("#spotShareDetails #embed_spot").val(embedHTML);
		*/
		$("#spotShareDetails #link_spot").text("http://us.repstars.com/my/spots/show?fn_spot_id=" + tempspotid).attr("href", "http://us.repstars.com/my/spots/show?fn_spot_id=" + tempspotid);
		$("#spotShareDetails #link_spot_text").val("http://us.repstars.com/my/spots/show?fn_spot_id=" + tempspotid);
		$("#spotShareDetails input[name='spot_btn']").unbind("click");
		$("#spotShareDetails input[name='spot_btn']").change(function() {											   
			//alert(this.value);	
			var linkHTML = '<a href="http://us.repstars.com/my/spots/show?fn_spot_id=' + tempspotid + '" target="_blank">';
			linkHTML += '<img src="' + this.value + '" border="0"></a>';
			$("#spotShareDetails #btn_spot").val(linkHTML);
		});
		//alert(embedHTML);
	});
	
	$(".spot_delete").click(function() {
		var spotName = $(this).attr("rel");
		var confirmDelete = confirm("You are about to delete the SPOT - " + spotName + "." + "\n\n" + "Doing so will permanently remove this SPOT from your available SPOTs and inactivate it anywhere you may have already used it." + "\n\n" + "Are you sure you would like to delete this SPOT?");
		
		if (confirmDelete) {
			return true;
		} else {
			return false;
		}
	});
	
	$(".icw_enable").click(function() {
		$(this).parent().find("img").show();
		var icw_switch;
		var spotID = this.value;
		if(this.checked) {
			//alert("checked");
			icw_switch = 1;
			
		} else {
			//alert("unchecked");
			icw_switch = 0;
		}
		
		$.post("/my/spots/toggle_icw",{
  		fn_spot_id: this.value,
		fv_switch: icw_switch
		},function(xml){
			tempstatus = xml;
			//alert(tempstatus);
			//tempmsg = $("request > message",xml).text();
			
			$("input.icw_enable[value='"+spotID+"']").parent().find("img").hide();
			
			if (tempstatus == 1) { 
				$("input.icw_enable[value='"+spotID+"']").attr("checked", "checked");
			} else {
				$("input.icw_enable[value='"+spotID+"']").removeAttr("checked"); 
			}
			
		 });
		return false;
	});
	$(".ar_ajax:checkbox").bind('click',function () {
		//$(this).parents('tr').find("img.ajax_loader").show();
		$(this).parents('tr').find('td').css('background-color','#DDDDDD');
		var icw_switch;
		var arID = $(this).parents('tr').find('input[name=fn_autoresponder_id]').val();
		if($(this).parents('tr').find(':checkbox').is(':checked')) {
			//alert("checked");
			icw_switch = 0;
			
		} else {
			//alert("unchecked");
			icw_switch = 1;
		}
		
		$.post("/my/autoresponders/update_ar",{
  		fn_autoresponder_id: arID,
        fn_email_days: $(this).parents('tr').find('select[name=fn_email_days]').val(),
		fn_email_enable: icw_switch,
        fv_email_clob: $(this).parents('tr').find('input[name=fv_email_clob]').val(),
        fn_type: $(this).parents('tr').find('input[name=fn_type]').val()
		},function(xml){
			tempstatus = xml;
			//alert(tempstatus);
			//tempmsg = $("request > message",xml).text();
			
			//$(".ar"+arID).find("img.ajax_loader").hide();
			$(".ar"+arID).find('td').css('background-color','#DDFFDD');
			setTimeout("$('.ar"+arID+"').find('td').css('background-color','');",500);
			/*if (tempstatus == 1) { 
				$("input.icw_enable[value='"+arID+"']").attr("checked", "checked");
			} else {
				$("input.icw_enable[value='"+arID+"']").removeAttr("checked"); 
			}*/
			
		 });
	});
	$(".ar_ajax").bind('change',function () {
		//$(this).parents('tr').find("img.ajax_loader").show();
		$(this).parents('tr').find('td').css('background-color','#DDDDDD');
		var icw_switch;
		var arID = $(this).parents('tr').find('input[name=fn_autoresponder_id]').val();
		if($(this).parents('tr').find(':checkbox').is(':checked')) {
			//alert("checked");
			icw_switch = 0;
			
		} else {
			//alert("unchecked");
			icw_switch = 1;
		}
		
		$.post("/my/autoresponders/update_ar",{
  		fn_autoresponder_id: arID,
        fn_email_days: $(this).parents('tr').find('select[name=fn_email_days]').val(),
		fn_email_enable: icw_switch,
        fv_email_clob: $(this).parents('tr').find('input[name=fv_email_clob]').val(),
        fn_type: $(this).parents('tr').find('input[name=fn_type]').val()
		},function(xml){
			tempstatus = xml;
			//alert(tempstatus);
			//tempmsg = $("request > message",xml).text();
			
			//$(".ar"+arID).find("img.ajax_loader").hide();
			$(".ar"+arID).find('td').css('background-color','#DDFFDD');
			setTimeout("$('.ar"+arID+"').find('td').css('background-color','');",500);
			/*if (tempstatus == 1) { 
				$("input.icw_enable[value='"+arID+"']").attr("checked", "checked");
			} else {
				$("input.icw_enable[value='"+arID+"']").removeAttr("checked"); 
			}*/
			
		 });
	});
	
	// *********************SPOT Configure Scripts End Here ******************
});


function getpreviewSWF() {
	if ((spottype != "") && (spotsize != "") && (spottheme != "")) {
		//alert("spottype = "+spottype+"; spotsize = "+spotsize);
		$.post("/my/spots/spot_swf",{
  		fn_height: spotsize,
		fn_type: spottype,
		fn_theme: spottheme
		},function(xml){
			tempspotid = $("spotfile",xml).attr("id");
			spotfile = $("spotfile > file",xml).text();
			spotInfo = xml;
			$("input[name='fn_spot_file_id']").val(tempspotid);
		 	buildPreviewSWF();
		 });
	}
}

function buildPreviewSWF() {
	//alert(spotfile);
	switch (spotfile) {
	case "/archive/spot/spot_video.swf":
  		swfwidth = '332';
		swfheight = '490';
 		break;
	case "/archive/spot/spot_video_sm.swf":
  		swfwidth = '252';
		swfheight = '373';
 		break;
	case "/archive/spot/spot_video_fb.swf":
  		swfwidth = '160';
		swfheight = '205';
 		break;
	case "/archive/spot/spot_video_fb_2.swf":
  		swfwidth = '184';
		swfheight = '250';
 		break;
	case "/archive/spot/spot_prospect.swf":
  		swfwidth = '332';
		swfheight = '290';
 		break;
	case "/archive/spot/spot_prospect_sm.swf":
  		swfwidth = '252';
		swfheight = '253';
 		break;
	case "/archive/spot/spot_call.swf":
  		swfwidth = '332';
		swfheight = '190';
 		break;
	case "/archive/spot/spot_call_sm.swf":
  		swfwidth = '252';
		swfheight = '178';
 		break;
	default:
  		alert("There is no file that matches this configuration");
	}
	
	var so = new SWFObject(spotfile,'jstest',swfwidth,swfheight,'9');
  	so.addParam('allowscriptaccess','always');
  	so.addParam('allowfullscreen','true');  
  	so.addParam('wmode','transparent');
  	so.addParam('menu','true');
	so.addVariable('p','true');
	so.addVariable('javascriptid','jstest');
  	so.addVariable('enablejs','true');
	so.addVariable('tt', $("spotfile > theme > backgroundid",spotInfo).text());
	so.addVariable('tn', previewName);
	so.addVariable('tp', previewPhone);
	so.addVariable('te', previewEmail);
	so.addVariable('thead',$("spotfile > theme > headerVars",spotInfo).text());
	so.addVariable('tbutton',$("spotfile > theme > buttonColors",spotInfo).text());
	so.addVariable('tother',$("spotfile > theme > otherColors",spotInfo).text());
	so.addVariable('tlogo',$("spotfile > theme > logoUrl",spotInfo).text());
	so.addVariable('tmessage',$("spotfile > theme > tmessage",spotInfo).text());
	so.addVariable('tlink',$("spotfile > theme > tlink",spotInfo).text());
	
	var tempvidid = $("input[name='fn_share_media_id']").val();
	var tempmessage = $("input[name='fv_message']").val();
	var tempbutton = $("input[name='fv_button_text']").val();
	var tempcontact;
	$("input[name='fn_contact_info']").each(function() { if (this.checked == true) { tempcontact=this.value } });
	var tempict = $("input[id='fn_ict_enable']").val();
	var tempurl = $("input[id='fv_forward_url']").val();
	var tempvid = "";
	var tempthumb = "";
	if (tempvidid != "") {	
		var tempvid = "enc/flv/" + $("input#video_url").val();
		var tempthumb = "enc/lg/" + $("input#video_thumb").val();
		//alert(tempvid+"-->"+tempthumb);
	}
	so.addVariable('file',tempvid);
	so.addVariable('image',tempthumb);
	
	if (tempmessage != "") { so.addVariable('tm',tempmessage); }
	if (tempbutton != "") { so.addVariable('tb',tempbutton); }
	//alert(tempcontact);
	if (tempcontact != "") { so.addVariable('tc',tempcontact); }
	//if (tempict != "") { so.addVariable('ti',tempict); }
	//if (tempurl != "") { so.addVariable('tu',tempurl); }
  	
  	so.write('spot_preview');
	if($("spotfile > theme > backgroundid",spotInfo).text() == 4) {
		$("#spot_preview").css("background", "none");
		$("#spot_preview").css("background", "#333333");		
	} else
		$("#spot_preview").css("background", "none");
}


function getVideoThumbs(page, browse, listsort, tags, opp, cat, firstvideo, network, user, firstplay) {
	page = (page == undefined) ? "" : page;
	browse = (browse == undefined) ? "" : browse;
	listsort = (listsort == undefined) ? "" : listsort;
	tags = (tags == undefined) ? "" : tags;
	opp = (opp == undefined) ? "" : opp;
	cat = (cat == undefined) ? "" : cat;
	firstvideo = (firstvideo == undefined) ? "" : firstvideo;
	network = (network == undefined) ? "" : network;
	user = (user == undefined) ? "" : user;
	firstplay = (firstplay == undefined) ? false : firstplay;
	
	$.ajax({
  		type: "POST",
  		url: "/gsnapi/xml_media",
  		dataType: "xml",
  		data: {
  			p: page,
			b: browse,
			s: listsort,
			t: tags,
			o: opp,
			c: cat,
			v: firstvideo,
			n: network,
			u: user
		},
		beforeSend: function(xhr) {
    		xhr.setRequestHeader( "Connection", "close" );
		},
  		success: function(xml) {
    		pltotal = $("allmedia > total",xml).text();
			if (pltotal > plcount) {
				$("allmedia > media",xml).each(function() {						
					tempmediaid = $("id", this).text();
					tempfilename = $("filename", this).text();
					temptype = $("type", this).text();
					temptitle = $("title", this).text();
					tempdescription = $("description", this).text();
					tempuser = $("user", this).text();
					templength = $("length", this).text();
					tempviews = $("views", this).text();
					tempthumb = $("thumbnailimage", this).text();
					tempkeywords = $("keywords", this).text();
					tempwebimage = $("websiteimage", this).text();
					tempweburl = $("websiteurl", this).text();
					tempnetwork = $("networkid", this).text();
					pl.push([tempmediaid, tempfilename, temptype, temptitle, tempdescription, tempuser, templength, tempviews, tempthumb, tempkeywords, tempwebimage, tempweburl, tempnetwork]);
				});
				createThumbs(firstplay);
			}
  		}
	});

}

function createThumbs(firstplay) {
	var listHTML = "";
	for (i=plcount;i<pl.length;i++) {
		if ((firstplay) && (plcount == 0)) { 
			videoplaying = pl[i][0]; 
			//$("#media_share #fv_embed").val('<embed src="http://' + document.location.host + '/swf" width="400" height="245" allowfullscreen="true" wmode="opaque" flashvars="&displayheight=225&file=http://media.repstars.com/enc/flv/' + pl[i][1] + '&height=245&image=http://media.repstars.com/enc/lg/' + pl[i][8] + '&width=400&screencolor=0x000000"></embed>');
			//$("#media_share #fv_link").val("http://" + document.location.host + "/home?V=" + pl[i][0] + "&N=" + pl[i][12]);
			//if ((pl[i][10] != "") && (pl[i][11] != "")) {
				//$("#media_website").html('<a href="http://' + pl[i][11] + '" target="_blank"><img src="' + pl[i][10] + '" border="0" /></a>' + label_moreinfo_1);
			//} else {
				//$("#media_website").html(label_moreinfo_2);
			//}
		}
		listHTML += ((firstplay) && (plcount == 0)) ? "<li class='nowplaying'>" : "<li>";
		listHTML += "<a href='http://media.repstars.com/enc/flv/" + pl[i][1] + "' id='vid" + plcount + "'>";
		listHTML += "<img src='http://media.repstars.com/enc/sm/" + pl[i][8] + "' />";
		listHTML += "<strong>";
		if (pl[i][3].length > 24) { listHTML +=  pl[i][3].substr(0,24) + "..."; } else { listHTML +=  pl[i][3]; }
		listHTML += "</strong></a><br>By: "
		if (pl[i][5].length > 11) { listHTML +=  pl[i][5].substr(0,11) + "..."; } else { listHTML +=  pl[i][5]; }
		//listHTML += "Views: " + pl[i][7]  + "<br>";
		listHTML += "<br><span class='quiet' rel='" + pl[i][6] + "'>";
		//listHTML += ((firstplay) && (plcount == 0)) ? label_now_playing : "(" + pl[i][6]  + ")";
		listHTML += "</span></li>";
		plcount++;
	}
	
	if (plcount > (plcurrentpage * plbrowse)) { plnextpage++;}
		
	$("#media_playlist #videothumbs ul").width(plwidth*plnextpage).append(listHTML);
	$("#media_playlist #videothumbs li a").unbind("click");
	$("#media_playlist #videothumbs li a").click(function () {
		//alert("Vido File is: " + this.href);
		currentvideo = $(this).attr("id");
		currentvideo = currentvideo.substring(3);
		currentvideo = currentvideo*1;
		
		//$("#icon_details").click();
		
		var thumb = "http://media.repstars.com/enc/lg/" + pl[currentvideo][8];
		$("#media_details h2").text(pl[currentvideo][3]);
		$("#media_details #media_by a").text(pl[currentvideo][5]);
		$("#media_details #media_views span").text(pl[currentvideo][7]);
		//var videosummary =  (pl[currentvideo][4] != "") ? pl[currentvideo][4] : "<span class='quiet'>" + label_nosummary + "</span>";
		var videosummary =  (pl[currentvideo][4] != "") ? pl[currentvideo][4] : "<span class='quiet'>Need Label Here</span>";
		$("#media_details #media_summary").html(videosummary);
		//$("#media_flag input[name='fv_video_id']").val(pl[currentvideo][0]);
		//$("#media_contact input[name='fv_video_id']").val(pl[currentvideo][0]);
		//$("#media_contact input[name='fv_username']").val(pl[currentvideo][5]);
		
		//$("#media_share #fv_link").val("http://" + document.location.host + "/home?V=" + pl[currentvideo][0] + "&N=" + pl[currentvideo][12]);
		//$("#media_share #fv_embed").val('<embed src="http://' + document.location.host + '/jw_media_player/mediaplayer.swf" width="400" height="245" allowfullscreen="true" wmode="opaque" flashvars="&displayheight=225&file=' + this.href + '&height=245&image=' + thumb + '&width=400&screencolor=0x000000"></embed>');
		
		/*if ((pl[currentvideo][10] != "") && (pl[currentvideo][11] != "")) {
			$("#media_website").html('<a href="http://' + pl[currentvideo][11] + '" target="_blank"><img src="' + pl[currentvideo][10] + '" border="0" /></a>' + label_moreinfo_1);
		} else {
			$("#media_website").html(label_moreinfo_2);
		}*/
		
		videoplaying = pl[currentvideo][0];
		var keywords = pl[currentvideo][9]; 
		keywords = keywords.replace(/,/g, " ");
		var tags = keywords.split(" ");
		var taghtml = "";
		for(i = 0; i < tags.length; i++){
			taghtml += "<a href='#' class='searchtag'>" + tags[i] + "</a> ";
		}
		$("#media_details #media_tags span").html(taghtml);
		
		/*$("#media_details .searchtag").click(function() {
			var searchtag = $(this).text();
			$("#videosearch #videotags").val(searchtag);
			$("#videosearch button").click();
			return false;
		});*/
		
		$("#media_details .searchtag").click(function() {
		if (scrollswitch) {
			plsearch = $(this).text();	
			//$("#all_playlists h1#current span").text(label_pl_current_1 + " '" + plsearch + "'");
			pl.length = 0; // clear array
			plcurrentpage = 1; // reset current page back
			plnextpage = 1; // reset next page
			plcount = 0; // reset playlist count
			plopp = ""; // reset browse by opportunity
			plcat = ""; //reset browse by category
			plvideo = videoplaying; //video currently loaded
			plnetwork = ""; //reeset network group
			pluser = ""; //reser user
			currentvideo = 0;
			//alert("video id="+plvideo);
			$("#media_playlist #videothumbs ul").width(plwidth*2).css("margin-left", 0).empty();
			getVideoThumbs(plcurrentpage, firstplbrowse, plsort, plsearch, plopp, plcat, plvideo, plnetwork, pluser, true);	
		}		
		return false;						
	});
		
		loadFile('jstest',{file:this.href, image:thumb});
		if (autoclick) { setTimeout("sendEvent('jstest','playpause')", 500); }
		autoclick = false;
		
		$("#media_playlist #videothumbs li").each(function () { 
			$(this).removeClass("nowplaying");
			var playlength = $(this).find("span.quiet").attr("rel");
			$(this).find("span.quiet").text("(" + playlength + ")");
		});
		$(this).parent().addClass("nowplaying");//.find("span.quiet").text(label_now_playing);
		return false;
	});
	
	//if (firstplay) { playNextVideo(); }
}

function loadFile(swf,obj) { 
  thisMovie(swf).loadFile(obj); 
};

function sendEvent(swf,typ,prm) { 
//alert("next video is: " + currentvideo);
  thisMovie(swf).sendEvent(typ,prm); 
};

function getUpdate(typ,pr1,pr2,swf) { 
//$("body").append("type="+typ+"; pr1="+pr1+"; pr2=" +pr2+"<br>"); //if(typ == "remaining") { alert('remaining: '+pr1); } 
if((typ == "state")&&(pr1 != undefined)) { 
				currentState = pr1; 
				if(currentState=="3") { playNextVideo(); }
			}
}

function playNextVideo() {
	//alert("nextvideo");
	if (!contactfocus) {
		autoclick = true;
		currentvideo++;
		var videocount = 0;
		$("#media_playlist #videothumbs li a").each(function() {
			if (videocount == currentvideo) { 
				$(this).click(); 
				if (videocount > (plcurrentpage * plbrowse - 1)) { $("#media_playlist #nextvideo a").click(); }
				//alert ("videocount= "+videocount+"; plcurrentpage= "+plcurrentpage+"; plbrowse= "+plbrowse+"; last thumb= "+(plcurrentpage * plbrowse));

			}		
			videocount++;
		});
	}
}

function thisMovie(swf) {
  if(navigator.appName.indexOf("Microsoft") != -1) {
    return window[swf];
  } else {
    return document[swf];
  }
};

function calculateOrderTotal() {
	var subtotal = 0;
	var discount = 0;
	var total = 0;
	$("#ordersum .prodline .price").each(function() {
		var priceString = $(this).html();
		//alert(priceString);
		var numPos = priceString.indexOf("$");
		var moPos = priceString.indexOf("/mo");
		if (moPos != -1) {
			var priceNum = priceString.substring(numPos+1,moPos) * 1;
		} else {
			var priceNum = priceString.substring(numPos+1) * 1;
		}
		//alert(priceNum);
		subtotal += priceNum;	
		//alert(subtotal);
	});
	$("#ordersum .prodcoupon .price").each(function() {
		var priceString = $(this).html();
		//alert(priceString);
		var numPos = priceString.indexOf("$");
		var moPos = priceString.indexOf("/mo");
		//var priceNum = priceString.substring(numPos+1) * 1;
		if (moPos != -1) {
			var priceNum = priceString.substring(numPos+1,moPos) * 1;
		} else {
			var priceNum = priceString.substring(numPos+1) * 1;
		}
		//alert(priceNum);
		discount += priceNum;	
		//alert(discount);
	});
	
	total = subtotal - discount;
	$("#prodsubtotal .price").html("$" + subtotal.toFixed(2));
	$("#proddiscount .price").html("-$" + discount.toFixed(2));
	$("#prodtotal .price").html("$" + total.toFixed(2));
	//alert(total);
}

function removeSetupCoup() {
	var removeMyCoup = confirm("Are you sure you want to remove this coupon?");
	if (removeMyCoup) {
		$("#setupcoupon .desc").html("");
		$("#setupcoupon .price").html("");
		$("#setupcoupon").hide();
		$("#fv_setup_coupon").val("");
	}
	calculateOrderTotal();
	return false;
}
	
function removeProdCoup() {
	var removeMyCoup = confirm("Are you sure you want to remove this coupon?");
	if (removeMyCoup) {
		$("#prodpackagecoupon .desc").html("");
		$("#prodpackagecoupon .price").html("");
		$("#prodpackagecoupon").hide();
		$("#fv_prod_coupon").val("");
	}
	calculateOrderTotal();
	return false;
}

function updateProdCoupon(couponcode) {
	if (couponcode != "") {
		for (i=0; i<coups.length;i++) {
			if (coups[i][0] == couponcode)	{
				//alert("array works --> " + prods[i]);
					if(couponcode.substr(0,7) == 'CB30DAY') {
						$("#prodpackagecoupon .desc").html("Full Discount for Entry Level Service");
					} else {
						$("#prodpackagecoupon .desc").html("Coupon Code: " + coups[i][0]);
					}
                if (coups[i][1]=="") {
					$("#prodpackagecoupon .desc").append(" - " + coups[i][2] + "% OFF");
					var prodPrice = $("#prodpackage .price").text();
					prodPrice = prodPrice.substring(1);						
					var moPos = prodPrice.indexOf("/mo");
					prodPrice = prodPrice.substring(0,moPos);
					//alert(prodPrice);
					var couponDiscount = prodPrice * (coups[i][2] * .01);						
					$("#prodpackagecoupon .price").html("-$" + couponDiscount.toFixed(2) + "/mo");
                }  else {
					var couponDiscount = coups[i][1]*1;
					$("#prodpackagecoupon .price").html("-$" + couponDiscount.toFixed(2) + "/mo");
                }
				if (document.location.href != "http://us.repstars.com/my/registration/thanks") {
					var removeHTML = '<br /><a href="#" onclick="removeProdCoup();">Remove Coupon</a>';
					$("#prodpackagecoupon .desc").append(removeHTML);
				}
				$("#prodpackagecoupon").show();
			} 
		}
	}
	calculateOrderTotal();
}
	
function validateSubscribe(colID) {
		var selection1 = "#" + colID + " input.check1";
		var selection2 = "#" + colID + " input.check2";
		var selection3 = "#" + colID + " input.check3";
		
		var check1;
		var check2;
		var check3;

		$(selection1).each(function() { check1 = this.checked });
		$(selection2).each(function() { check2 = this.checked });
		$(selection3).each(function() { check3 = this.checked });
		
		if ((check1 == false) || (check2 == false) || (check3 == false)) {
			alert("In order to complete the application process, you must indicate that you have read, understand and agree to abide by the documents indicated by checking the boxes provided.");
			return false; 
		} else {
			return true;
		}
	
}

function validateSubscribe2() {
		var selection = "#" + colID + " :checkbox";
		var allBoxes = false;
		//var numBoxes = $(selection).length;

		//var numBoxes = 3;
		var boxCount = 0;
		return false;
		
		
		/*$(selection).each(function() {
			boxCount++;
			alert("checkbox=" + this.checked);
			if ((this.checked != true) && (allBoxes == true)) {
				allBoxes = false;
				return allBoxes;
			}
			if (boxCount == numBoxes) { return allBoxes; }
			});*/
	
}



function setupBanner() {
	$("#banner").html("<span></span><div id='bannercontrols'><a href='#' id='banner_prev'>|&lt;</a> <a href='#' id='banner_play_pause' class='banner_pause'> &gt; </a> <a href='#' id='banner_next'> &gt;| </a></div>");
	
	$("#banner span").html(allheadlines[headlinecount]);
	$("#banner_prev").click(function () { bannerPrev(); });
	$("#banner_next").click(function () { bannerNext(); });
	$("#banner_play_pause").click(function () { bannerPause(); });
	
	startBannerTimer();
}

function startBannerTimer() {
	bannerInterval = window.setInterval( "bannerNext()", bannerTime );   
}
function resetBannerTimer() {
	window.clearInterval( bannerInterval );
	startBannerTimer();  
}
function bannerPause() {   
	var btnclass = $("#banner_play_pause").attr("class")
	if (btnclass == "banner_play") {
		$("#banner_play_pause").removeClass("banner_play");
		$("#banner_play_pause").addClass("banner_pause");
		startBannerTimer();
	} else {
		$("#banner_play_pause").removeClass("banner_pause");
		$("#banner_play_pause").addClass("banner_play");
		window.clearInterval( bannerInterval );
	}
}
function bannerPrev() {
	if (headlinecount > 0) {
		headlinecount--;
	} else {
		headlinecount = allheadlines.length-1
	}
	
	$("#banner span").hide("slow", function () {
		$(this).html(allheadlines[headlinecount]);	
		$(this).show("slow");
		});
	
	resetBannerTimer();
}
function bannerNext() {
	if (headlinecount < allheadlines.length-1) {
		headlinecount++;
	} else {
		headlinecount = 0;
	}
	$("#banner span").hide("slow", function () {
		$(this).html(allheadlines[headlinecount]);
		$(this).show("slow");
		});
	
	resetBannerTimer();
}

function adjustPosition(obj, objtop, objleft) {
	var newtop = obj.style.top;
	var newleft = obj.style.left;			
	var pxpos = newtop.indexOf('px');
	newtop = parseInt(newtop.substring(0, pxpos));			
	pxpos = newleft.indexOf('px');
	newleft = parseInt(newleft.substring(0, pxpos));
	
	var windowwidth = $(window).width();
	var toolwidth = $(".tooltip").width();
	var windowoffset = (newleft > (windowwidth - toolwidth)) ? toolwidth + objleft : 0;
	//alert(windowoffset + " --> " + windowwidth + " --> " + toolwidth + " --> " + newleft);
	
	newtop += objtop;
	newtop += "px";			
	newleft += (objleft - windowoffset);
	newleft += "px";
	obj.style.top = newtop;
	obj.style.left = newleft;
}

function popupWindow(winurl,winname,winfeatures)
{
     //This launches a new window and then
     //focuses it if window.focus() is supported.
     newwin = window.open(winurl,winname,winfeatures);
     setTimeout('newwin.focus();',250);     
}

function popupReportWindow(form,winfeatures)
{
     //This launches a new window to show an IPS Manager report.
     newwin = window.open('','IPSReportWindow',winfeatures);
     form.target='IPSReportWindow';
}

/*function resize() {
  var iframe = document.all.myaccount;
  iframe.height=document.frames("myaccount").document.body.scrollHeight;
  }*/
  
function getDocHeight(doc) {
  var docHt = 0, sh, oh;
  if (doc.height) docHt = doc.height;
  else if (doc.body) {
    if (doc.body.scrollHeight) docHt = sh = doc.body.scrollHeight;
    if (doc.body.offsetHeight) docHt = oh = doc.body.offsetHeight;
    if (sh && oh) docHt = Math.max(sh, oh);
  }
  if(docHt<500) docHt = 500;
  return docHt;
}

function resize(subchildheight) {
  var iframeName = "myaccount";
  var iframeWin = window.frames[iframeName];
  var iframeEl = document.getElementById? document.getElementById(iframeName): document.all? document.all[iframeName]: null;
  if ( iframeEl && iframeWin ) {
	  iframeEl.style.height = "auto"; // helps resize (for some) if new doc shorter than previous
	  try {
		  var iframeWinLoc = iframeWin.location;
		  var docHt = getDocHeight(iframeWin.document);
		  setNavActive(iframeWin.location.pathname);
		  //alert("in domain");
	  } catch (error) {
		  //alert("error found: out of domain");
		  var iframeWinLoc = location.hash;
		  if (iframeWinLoc) {			  
			  var docHt = parseIframeHeight(iframeWinLoc);
		  } else {
			//window.frames[0].frames[“grandChildIframeName”]
			if (subchildheight) {
				var docHt = parseIframeHeight(subchildheight);
			} else {
				var docHt = 1500;
			}
		  }
	  } finally {
		  if (docHt) iframeEl.style.height = docHt + 40 + "px";
		  // need to add to height to be sure it will all show
	  }	  
  }
  //setNavActive(iframeWin.location.pathname);
}

function parseIframeHeight(iframeWinLoc) {
	var temp = new Array();
	temp = iframeWinLoc.split('iframeheight:');
	var docHt = temp[1] * 1;
	//Minimum iFrame Height
	if(docHt<525) docHt = 525;
	return docHt;
}

function setNavActive(iframepath) {
	//var iframepath = iframeWin.location.pathname;
	var temp;
  	var charPos = iframepath.lastIndexOf("/");
  	iframepath = iframepath.substr(charPos+1);
	charPos = iframepath.indexOf(".");
        temp = iframepath.substring(0, charPos).toLowerCase();
        if (temp != "gsn_web_home") {
	iframepath = iframepath.substring(0, charPos).toLowerCase();
        }
  
  	$("#ic_catlnk a").each(function() {
		$(this).removeClass("catlinkactive");
		var linkpath = this.href;
		charPos = linkpath.lastIndexOf("/");
		linkpath = linkpath.substr(charPos+1);
		charPos = linkpath.indexOf(".");
                if (temp != "gsn_web_home") {
		linkpath = linkpath.substring(0, charPos).toLowerCase();
                }
		if (iframepath == linkpath) {
			temp = linkpath;
			$(this).addClass("catlinkactive");
		} /*else if ((iframepath == "gsn_web_profile.startup") && (linkpath == "gsn_web_profile.startupnav")) {
			$(this).addClass("catlinkactive");
		} else if ((iframepath == "gsn_web_affiliation_payments.startup") && (linkpath == "gsn_web_affiliation_payments.startupnav")) {
			$(this).addClass("catlinkactive");
		}*/
		
		});
}

function disableOtherSubmitButtons(submitButton) {
	if(!submitButton) {
		//alert("no object found");
		return;
	}

	if(!submitButton.type) {
		//alert("no type attribute");
		return;
	}

	if(submitButton.type != "submit") {
		//alert("no submit button");
		return;
	}

	if(!submitButton.form) {
		//alert("parentless button (no form)");
		return;
	}

	var formElements = submitButton.form.elements;

	for(var i=0; i<formElements.length; i++) {
		//leave the pressed button as is...
		if(formElements[i] == submitButton)
		continue;

		//disable all other submit buttons
		if(formElements[i].type == "submit") {
			formElements[i].disabled = "true";
		}
	}
}

function resizeExternal(docHt) {
  var iframeName = "myaccount";
  var iframeWin = window.frames[iframeName];
  var iframeEl = document.getElementById? document.getElementById(iframeName): document.all? document.all[iframeName]: null;
  if ( iframeEl && iframeWin ) {
    iframeEl.style.height = "auto"; // helps resize (for some) if new doc shorter than previous  
    // need to add to height to be sure it will all show
    if (docHt) iframeEl.style.height = docHt + 40 + "px";
  }
  alert("externally resized" + docHt);
}




function validateInfo(form)
{   return (
      checkString(document.forms[0].fv_realname,"Your Name") &&
      checkEmail(document.forms[0].fv_email)
    )
}
function checkEmailVal(email) {
   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
   var address = email;
   if(reg.test(address) == false)
      return false;
   else
   	return true;
}
browserName = navigator.appName;
browserVer = parseInt(navigator.appVersion);

ns3up = (browserName == "Netscape" && browserVer >= 3);
ie4up = (browserName.indexOf("Microsoft") >= 0 && browserVer >= 4);

function doPic(imgName) {
if (ns3up || ie4up) {
imgOn = ("" + imgName);
document.mainpic.src = imgOn;
   }
}
function get_timestamp() {
  var tt = new Date();
  var day = tt.getDate();
  if (day < 10) day = "0" + day;
  var monthNames = "JanFebMarAprMayJunJulAugSepOctNovDec";
  var month = monthNames.substring(3*tt.getMonth(),3*(tt.getMonth()+1));
  var hour = tt.getHours();
  if (hour > 12)
    {hour = hour - 12;
     var pm = "PM";}
  else var pm = "AM";
  if (hour < 10) hour = "0" + hour;
  var minute = tt.getMinutes();
  if (minute < 10) minute = "0" + minute;
  var second = tt.getSeconds();
  if (second < 10) second = "0" + second;
  var timezone = (-1 * tt.getTimezoneOffset() / 60);
  if (Math.floor(timezone) == timezone) timezone = timezone + ".";
  var tz = day + "-" + month + "-" + tt.getYear() + " " + hour + ":" + minute + ":" + second + " " + pm + " " + timezone;
  return tz;
}
function get_timezone() {
  var tt = new Date();
  var timezone = (-1 * tt.getTimezoneOffset() / 60);
  if (Math.floor(timezone) == timezone) timezone = timezone + ":00";
  return timezone;
}

/***********************************************************************
*******************Set Environment Path*********************************
***********************************************************************/
// Routine called by all HTML pages to dynamically set path between dev and demo environemnts for anchor and iframe tags. 
// setEnvPath should be called within the body tag using onLoad.
// Date Authored: 07/26/2005   Author: Henry Tavarez

function setEnvPath () {	
	var devEnv = '/ngsdev/';
	var demoEnv = '/ngsdemo/';
	var prodEnv = '/ngs/';
	var anchorTags = document.getElementsByTagName("a");
	var iframeTags = document.getElementsByTagName("iframe");
	
	// Get environment path from referring URL
	if (document.referrer != '') { 
  		urlString = document.referrer;
		endSlashPos = urlString.lastIndexOf("/");
  		urlString = urlString.substring(0,endSlashPos);
  		startSlashPos = urlString.lastIndexOf("/");
  		dadString = urlString.substring(startSlashPos+1,endSlashPos);
	} 
	
	// Reset path for all anchor tags in HTML document
	for (var i = 0; i < anchorTags.length; i++) {
		var getHref=anchorTags[i].href;		
		if (getHref.indexOf(devEnv) > -1) {
			getHref = getHref.replace(devEnv,'/'+dadString+'/');
			}
		else if (getHref.indexOf(demoEnv) > -1) {
			getHref = getHref.replace(demoEnv,'/'+dadString+'/');
			}
		else if (getHref.indexOf(prodEnv) > -1) {
			getHref = getHref.replace(prodEnv,'/'+dadString+'/');
			}
		anchorTags[i].href = getHref;
		} 
	
	// Reset src path for all iframe tags in HTML document
	for (i = 0; i < iframeTags.length; i++) {
		getHref = iframeTags[i].src;
		if (getHref.indexOf(devEnv) > -1) {
			getHref = getHref.replace(devEnv,'/'+dadString+'/');
			}
		else if (getHref.indexOf(demoEnv) > -1) {
			getHref = getHref.replace(demoEnv,'/'+dadString+'/');
			}
		else if (getHref.indexOf(prodEnv) > -1) {
			getHref = getHref.replace(prodEnv,'/'+dadString+'/');
			}
		iframeTags[i].src = getHref;
		}
	}


function getElementsByAttribute(attribute, attributeValue)
{
  var elementArray = new Array();
  var matchedArray = new Array();

  if (document.all)
  {
    elementArray = document.all;
  }
  else
  {
    elementArray = document.getElementsByTagName("*");
  }

  for (var i = 0; i < elementArray.length; i++)
  {
    if (attribute == "class")
    {
      var pattern = new RegExp("(^| )" + attributeValue + "( |$)");

      if (elementArray[i].className.match(pattern))
      {
        matchedArray[matchedArray.length] = elementArray[i];
      }
    }
    else if (attribute == "for")
    {
      if (elementArray[i].getAttribute("htmlFor") || elementArray[i].getAttribute("for"))
      {
        if (elementArray[i].htmlFor == attributeValue)
        {
          matchedArray[matchedArray.length] = elementArray[i];
        }
      }
    }
    else if (elementArray[i].getAttribute(attribute) == attributeValue)
    {
      matchedArray[matchedArray.length] = elementArray[i];
    }
  }

  return matchedArray;
}


function addLoadListener(fn)
{
  if (typeof window.addEventListener != 'undefined')
  {
    window.addEventListener('load', fn, false);
  }
  else if (typeof document.addEventListener != 'undefined')
  {
    document.addEventListener('load', fn, false);
  }
  else if (typeof window.attachEvent != 'undefined')
  {
    window.attachEvent('onload', fn);
  }
  else
  {
    var oldfn = window.onload;
    if (typeof window.onload != 'function')
    {
      window.onload = fn;
    }
    else
    {
      window.onload = function()
      {
        oldfn();
        fn();
      };
    }
  }
}

function trim(str, chars) {
    return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

function addContactTypeSubmit() {
	//alert('adding group');
	$.get('/my/prospecting/add_type?fv_title='+escape($('#contact_type_title').val()),
  			function(data){
				//var myOptions = new Array;
				//myOptions[(data+"").replace(/[^0-9]+/g,'')] = $('#contact_type_title').val();
				
				/*var myOptions = {
	data : $('#contact_type_title').val()
	}*/
	//$("#fn_contact_list").addOption(myOptions, true); 
	//alert(data);
	window.location = '/my/prospecting/manage_groups';
	
  			}
		);
	
	$('#addContactType').hide();
	
	return false;
	
}



/*****************************************************************
*******************Form Field Highlight*********************************
****************************************************************
function addEvent(obj, evType, fn){
 if (obj.addEventListener){
    obj.addEventListener(evType, fn, true);
    return true;
 } else if (obj.attachEvent){
    var r = obj.attachEvent("on"+evType, fn);
    return r;
 } else {
    return false;
 }
} 
addEvent(window, 'load', function() {
 var input, textarea;
 var inputs = document.getElementsByTagName('input');
 for (var i = 0; (input = inputs[i]); i++) {
   addEvent(input, 'focus', oninputfocus);
   addEvent(input, 'blur', oninputblur);
 }
 var textareas = document.getElementsByTagName('textarea');
 for (var i = 0; (textarea = textareas[i]); i++) {
   addEvent(textarea, 'focus', oninputfocus);
   addEvent(textarea, 'blur', oninputblur);
 }
});
function oninputfocus(e) {
 //Cookie-cutter code to find the source of the event
 if (typeof e == 'undefined') {
   var e = window.event;
 }
 var source;
 if (typeof e.target != 'undefined') {
    source = e.target;
 } else if (typeof e.srcElement != 'undefined') {
    source = e.srcElement;
 } else {
   return;
 }
 //End cookie-cutter code
 if (source.className!='ips_formsubmit') {
 source.className='ips_formtexthilite';
 }
}
function oninputblur(e) {
 //Cookie-cutter code to find the source of the event
 if (typeof e == 'undefined') {
   var e = window.event;
 }
 var source;
 if (typeof e.target != 'undefined') {
    source = e.target;
 } else if (typeof e.srcElement != 'undefined') {
    source = e.srcElement;
 } else {
   return;
 }
 //End cookie-cutter code 
 if (source.className!='ips_formsubmit') {
 source.className='ips_formtext';
 }
}*/
function getFormattedPhoneNumber(zandais) {
	var a = zandais.replace(/[^0-9]/g, '');
	if(a.length == 7) {//ZONE 1 - NANP
												return a.substr(0,3)+' '+a.substr(3);
											} else if(a.length == 10) {//NANP Guess
												return a.substr(0,3)+' '+a.substr(3,3)+' '+a.substr(6);
											} else if(a.substr(0,1) == '1' && a.length>=11) {//Zone 1 – NANP
												return '+'+a.substr(0,1)+' '+a.substr(1,3)+' '+a.substr(4,3)+' '+a.substr(7);
											} else if(a.substr(0,1) == '2' && a.length>=10) {//Zone 2 – Mostly Africa, some Atlantic and Indian Ocean islands
													if(a.substr(0,2)!=27 &&a.substr(0,2)!=20) {
													b = '+'+a.substr(0,3)+' ';
													b += a.substr(3);
													} else {
														b = '+'+a.substr(0,2)+' ';
													b += a.substr(2);
													}
													return b;
											} else if((a.substr(0,1) == '3' || a.substr(0,1) == '4') && a.length>=10 && a.substr(0,2) != '44') {//Zone 3/4 - Europe
												var twodigits = [ 30, 31, 32, 33, 34, 36, 39, 40, 41, 43, 44, 45, 46, 47, 48, 49 ];
												twodigits = twodigits.toString();
												
												if(twodigits.search(a.substr(0,2)) == -1) {
													b = '+'+a.substr(0,3)+' ';
													b += a.substr(3);
													} else {
														b = '+'+a.substr(0,2)+' ';
													b += a.substr(2);
													}
													return b;
											} else if((a.substr(0,1) == '5') && a.length>=10) {//Zone 5 - Mexico, Central America and South America
												var twodigits = [ 51, 52, 53, 54, 55, 56, 57, 58 ];
												twodigits = twodigits.toString();
												
												if(twodigits.search(a.substr(0,2)) == -1) {
													b = '+'+a.substr(0,3)+' ';
													b += a.substr(3);
													} else {
														b = '+'+a.substr(0,2)+' ';
													b += a.substr(2);
													}
													return b;
													
                    					} else if((a.substr(0,1) == '6') && a.length>=10) {		//Zone 6 – Southeast Asia and Oceania
												var twodigits = [ 61, 62, 63, 64, 65, 66 ];
												twodigits = twodigits.toString();
												
												if(twodigits.search(a.substr(0,2)) == -1) {
													b = '+'+a.substr(0,3)+' ';
													b += a.substr(3);
													} else {
														b = '+'+a.substr(0,2)+' ';
													b += a.substr(2);
													}
													return b;
										} else if((a.substr(0,1) == '7') && a.length>=10) {		//Zone 7 – Seventh World Numbering Zone (former Soviet Union)
	     											b = '+7 ';
													b += a.substr(1,3)+' ';
													b += a.substr(4);
													return b;
													
													 
											} else if((a.substr(0,1) == '8') && a.length>=10) {		//Zone 8 - East Asia and Special Services
												var twodigits = [ 81, 82, 84, 86 ];
												twodigits = twodigits.toString();
												
												if(twodigits.search(a.substr(0,2)) == -1) {
													b = '+'+a.substr(0,3)+' ';
													b += a.substr(3);
													} else {
														b = '+'+a.substr(0,2)+' ';
													b += a.substr(2);
													}
													return b;
													
											} else if((a.substr(0,1) == '9') && a.length>=10) {		//Zone 9 - West, South and Central Asia
												var twodigits = [ 90,91,92,93,94,95,98 ];
												twodigits = twodigits.toString();
												
												if(twodigits.search(a.substr(0,2)) == -1) {
													b = '+'+a.substr(0,3)+' ';
													b += a.substr(3);
													} else {
														b = '+'+a.substr(0,2)+' ';
													b += a.substr(2);
													}
													return b;
										}  else if(a.substr(0,2) == '44' && a.length>=10) {//UK
													b = '+44 ';
													/*if(a.substr(2,1)== '1'&&a.substr(4,1)=='1') {
														b += ' '+a.substr(2,3) +' '+a.substr(5);		
													} else */if(a.substr(2,1)== '1') {
														b += a.substr(2,3) +' '+a.substr(5,3)+' '+a.substr(8);	
													} else if( a.substr(2,1)=='2') {
														b += a.substr(2,2)+' '+a.substr(4,4)+' '+a.substr(8);	
													} else {
														b += a.substr(2,3) +' '+a.substr(5,3)+' '+a.substr(8);
													}
													return b;
											} else
											    return a;				
}

/* The following is all related to active_content.js */
// Passing an example of array of arguments to both
// the success and failure callback handlers.
/* Please see the Success Case section for more
 * details on the response object's properties.
 * o.tId
 * o.status
 * o.statusText
 * o.getResponseHeader[ ]
 * o.getAllResponseHeaders
 * o.responseText
 * o.responseXML
 * o.argument
 */
var last_to_lang = "NULL";

var args = ['foo','bar'];

//Media Browser
var responseSuccess = function(o){
 document.getElementById("media_related").innerHTML = o.responseText;
};

var responseFailure = function(o){
	document.getElementById("media_related").innerHTML = "error"+o.responseText;
}

//Media Player
var responseSuccessb = function(o){
 document.getElementById("media_player_center").innerHTML = o.responseText;
 tag_build();
};

var responseFailureb = function(o){
	document.getElementById("media_player_center").innerHTML = "error"+o.responseText;
}

//Ratings Startup
var responseSuccessc = function(o){
	ratings_open();
 	document.getElementById("ratingz_overlay").innerHTML = o.responseText;
};

var responseFailurec = function(o){
	ratings_open();
	document.getElementById("ratingz_overlay").innerHTML = "error"+o.responseText;
}
var responseSuccessd = function(o){

	document.getElementById("ratingz_overlay").innerHTML = o.responseText;
};

var responseFailured = function(o){
	
	document.getElementById("ratingz_overlay").innerHTML = "error"+o.responseText;
	//ratings_open();
}
var responseSuccesstrans = function(o){
 	document.getElementById(("trans_"+last_to_lang)).innerHTML = o.responseText;
};

var responseFailuretrans = function(o){
	document.getElementById(("trans_"+last_to_lang)).innerHTML = "error: "+o.responseText;
}
var responseSuccessgene = function(o){
	open_genealogy();
	document.getElementById("genealogy_overlay").innerHTML = o.responseText;
};

function moveObject( obj, e, edittoponly ) {

  // step 1
  var tempX = 0;
  var tempY = 0;
  var offset = 5;
  var objHolder = obj;
  if(edittoponly==null)
	  edittoponly = false;

  // step 2
  obj = document.getElementById(obj); //getObject( obj );
  if (obj==null) return;

  // step 3
  if (document.all) {
    tempX = event.clientX + document.body.scrollLeft;
    tempY = event.clientY + document.body.scrollTop;
  } else {
    tempX = e.pageX;
    tempY = e.pageY;
  }
  tempX -= 20;
  tempY -= 20;
  // step 4
  if (tempX < 0){tempX = 0}
  if (tempY < 0){tempY = 0}
if (tempX > getPageSizeWithScroll()[0]-320){tempX = getPageSizeWithScroll()[0]-320; }
if(edittoponly && tempY > getPageSizeWithScroll()[1]-450) {tempY = getPageSizeWithScroll()[1]-450; }
if(edittoponly == false && tempY > getPageSizeWithScroll()[1]-350) {tempY = getPageSizeWithScroll()[1]-350; }
// step 5
  obj.style.top  = (tempY + offset) + 'px';
  if(edittoponly==false)
  	obj.style.left = (tempX + offset) + 'px';

  // step 6
  //displayObject( objHolder, true );
  }
function getPageSizeWithScroll(){
	if (window.innerHeight && window.scrollMaxY) {// Firefox
		yWithScroll = window.innerHeight + window.scrollMaxY;
		xWithScroll = window.innerWidth + window.scrollMaxX;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		yWithScroll = document.body.scrollHeight;
		xWithScroll = document.body.scrollWidth;
	} else { // works in Explorer 6 Strict, Mozilla (not FF) and Safari
		yWithScroll = document.body.offsetHeight;
		xWithScroll = document.body.offsetWidth;
  	}
	PageSizeWithScroll = Array(xWithScroll,yWithScroll);
	//alert( 'The height is ' + yWithScroll + ' and the width is ' + xWithScroll );
	return PageSizeWithScroll;
}
var responseFailuregene = function(o){
	document.getElementById("genealogy_overlay").innerHTML = "error: "+o.responseText;
}
var callback =
{
  success:responseSuccess,
  failure:responseFailure,
  argument:args
};
var callbackb =
{
  success:responseSuccessb,
  failure:responseFailureb,
  argument:args
};
var callbackc =
{
  success:responseSuccessc,
  failure:responseFailurec,
  argument:args
};
var callbackd =
{
  success:responseSuccessd,
  failure:responseFailured,
  argument:args
};
var callbacktrans =
{
  success:responseSuccesstrans,
  failure:responseFailuretrans,
  argument:args
};
var callbackgene =
{
  success:responseSuccessgene,
  failure:responseFailuregene,
  argument:args
};



function browseby(action,start) {
	
		sUrl = "/pls/ngs/gsn_web_media_sharing.browse?ms_browse_action="+action+"&ms_browse_start="+start;
    var transaction = YAHOO.util.Connect.asyncRequest('GET', sUrl, callback, null);
}
function playvideo(id) {
	sUrl = "/pls/ngs/gsn_web_media_sharing.playvideo?fv_video_id="+id;
	
	var transaction = YAHOO.util.Connect.asyncRequest('GET', sUrl, callbackb, null);
}
function show_rating(subject,id,ftype,e) {
	//startup_feedback
	//startup_report
	moveObject( "ratingz_overlay", e, true );
	if(subject == 'feedback'||subject=='report')
		sUrl = "/pls/ngs/gsn_web_ratings_reviews.startup_feedrep?fv_subject="+subject+"&fv_object_id="+id+"&fv_feedback_type="+ftype;
	else
		sUrl = "/pls/ngs/gsn_web_ratings_reviews.startup?fv_rating_object="+subject+"&fn_object_id="+id+"&fv_feedback_type="+ftype;
	
	var transaction = YAHOO.util.Connect.asyncRequest('GET', sUrl, callbackc, null);
}
function rating_submit(subject,id,feedback_type) {
	review = document.getElementById("review").value;
	if(subject == 'feedback'||subject=='report') {
		ratingval = 0;
	} else {
		if(document.ratings.rating[0].checked)
			ratingval = 1;
		if(document.ratings.rating[1].checked)
			ratingval = 2;
		if(document.ratings.rating[2].checked)
			ratingval = 3;
		if(document.ratings.rating[3].checked)
			ratingval = 4;
		if(document.ratings.rating[4].checked)
			ratingval = 5;
	}
	sUrl = "/pls/ngs/gsn_web_ratings_reviews.rate?fv_feedback_type="+feedback_type+"&fv_rating_object="+subject+"&fn_object_id="+id+"&fn_rating="+ratingval+"&fv_comment="+escape(review);
	
	var transaction = YAHOO.util.Connect.asyncRequest('GET', sUrl, callbackd, null);
	ratings_close();
}

function change_iframe(subject,id) {
	sUrl = "/pls/ngs/gsn_web_ratings_reviews.startup?fv_rating_object="+subject+"&fn_object_id="+id;
	
	var transaction = YAHOO.util.Connect.asyncRequest('GET', sUrl, callbacke, null);
}

function trans_run(to_lang) {
	sUrl = "/pls/ngs/gsn_web_more_points.translation?to_lang="+to_lang;
	last_to_lang = to_lang;
	var transaction = YAHOO.util.Connect.asyncRequest('GET', sUrl, callbacktrans, null);
}

function add_node(id,recenter,e) {
	moveObject( "genealogy_overlay", e ); 
	sUrl = "/pls/ngs/gsn_web_prospecting.create_child_node?fn_node="+id+"&fv_recenter="+recenter;
	//window.location = sUrl;
	var transaction = YAHOO.util.Connect.asyncRequest('GET', sUrl, callbackgene, null);
}
function edit_node(id,recenter,e) {
	moveObject( "genealogy_overlay", e );
	sUrl = "/pls/ngs/gsn_web_prospecting.show_add_edit?fn_node="+id+"&fv_recenter="+recenter+"&fv_status=edit";
	
	var transaction = YAHOO.util.Connect.asyncRequest('GET', sUrl, callbackgene, null);
}
function delete_node(id,recenter,e) {
	moveObject( "genealogy_overlay", e );
	sUrl = "/pls/ngs/gsn_web_prospecting.show_add_edit?fn_node="+id+"&fv_recenter="+recenter+"&fv_status=delete";
	var transaction = YAHOO.util.Connect.asyncRequest('GET', sUrl, callbackgene, null);
}
/*function genealogy_submit_add(id,cust_id) {
	review = document.getElementById("review").value;
	sUrl = "/pls/ngs/gsn_cust_comp_genes.submitadd?fn_node="+id+"&fn_cust="+cust_id;
	
	var transaction = YAHOO.util.Connect.asyncRequest('GET', sUrl, callbackgenec, null);
}
function genealogy_submit_edit(id) {
	review = document.getElementById("review").value;
	sUrl = "/pls/ngs/gsn_cust_comp_genes.submitedit?fn_node="+id;
	
	var transaction = YAHOO.util.Connect.asyncRequest('GET', sUrl, callbackgenec, null);
}*/
function close_genealogy() {
	close_box('genealogy_overlay');
}
function open_genealogy() {
	open_box('genealogy_overlay');
}
function ratings_close() {
	close_box('ratingz_overlay');
}
function ratings_open() {
	open_box('ratingz_overlay');
}
function close_box(obj) {
	elem = document.getElementById(obj);
	vis = elem.style;
	if(vis.display==''&&elem.offsetWidth!=undefined&&elem.offsetHeight!=undefined)
    vis.display = (elem.offsetWidth!=0&&elem.offsetHeight!=0)?'block':'none';
  vis.display = (vis.display==''||vis.display=='block')?'none':'block';
 	elem.innerHTML = '';
}
function open_box(obj) {
	elem = document.getElementById(obj);
	vis = elem.style;
  	vis.display = 'block';
}
function show_gene_opts(ln_index) {
	return;
	elem = document.getElementById(('gene_opts'+ln_index));
	vis = elem.style;
	//tagz.style.display = (tagz.style.display==''||tagz.style.display=='block')?'none':'block';
	if(vis.display==''&&elem.offsetWidth!=undefined&&elem.offsetHeight!=undefined)
    	vis.display = (elem.offsetWidth!=0&&elem.offsetHeight!=0)?'block':'none';
  	vis.display = (vis.display==''||vis.display=='block')?'none':'block';
}
function lead_prospect(formnum) {
	if(formnum==0)
		formnum = '';
	
		
	a = $("#fv_first" + formnum).val();
	
	b = $("#fv_last"+formnum).val();
	
	c = $('#fv_email'+formnum).val();
	
	d = $('#fv_phone'+formnum).val();
	e = $('#fn_customer_id').val();
	f = $('#fn_email_flag'+formnum).attr('checked');
	
	if(f)
		f = 1;
	else
		f = 0;
	
	
	
	window.location = 'gsn_web_prospecting.create_prospect?fv_first='+a+'&fv_last='+b+'&fv_email='+c+'&fv_phone='+d+'&fn_customer_id='+e+'&fn_email_flag='+f;
}

/* The following is related to the "Translate this Page" Features */
var translator_data;
var trans_id;
var translations_on = 0;
var translate_hide;
var translate_show;
function loadTranslator() {
var ifrm = document.getElementById('TB_iframeContent');
ifrm = (ifrm.contentWindow) ? ifrm.contentWindow : (ifrm.contentDocument.document) ? ifrm.contentDocument.document : ifrm.contentDocument;
ifrm.document.open();
ifrm.document.write(translator_data);
ifrm.document.close();
}
$(document).ready(function() {
transcount = $(".trnsrec, .trnsimg").length;
untranslatedcount = $(".tfrEN").length;

if ( $("#enable_translate").length == 0 && iamtranslator ) {
	$("body").append('<div id="translate_ad" class="ad" title="Click to Open the Translation Widget" style="position:fixed; bottom:-160px; left:-136px; opacity:.45; -moz-opacity:.45; width:160px;"><a title="Translate Now" class="thickbox" href="/my/more_points/translation_widget?TB_iframe=true&amp;height=460&amp;width=500">Translate A Label Now</a><br/><strong>OR</strong><br/><div id="enable_translate"><a onclick="return false;" href="#">Enable All Translations For This Page</a></div></div>');
	$("#enable_translate_alt").click(function () { enableTranslation() });
	tb_init("#translate_ad a.thickbox");
	$("#translate_ad").click(function () {
									   clearTimeout(translate_hide);
										
										$("#translate_ad").stop(true);
										if($("#translate_ad").css('left') == '10px') {
											$("#translate_ad").animate({ bottom: "-160px",        opacity: .45,        left: "-136px"      }, 0 );
										} else {
										  $("#translate_ad").animate({ bottom: "10px",        opacity: 1,        left: "10px"      }, 500 );
										  
										}
										
									   });
	$("#translate_ad").hover(function() { 
										 $(this).attr('title','Click again to close');

										  
										  
		 } , function() { 
										$(this).attr('title','Click to Open the Translation Widget');
										// clearTimeout(translate_hide);
										 //-115px, -52px
										// translate_hide = setTimeout('$("#translate_ad").stop(true);$("#translate_ad").animate({ bottom: "-160px",        opacity: .45,        left: "-136px",      }, 0 );',500);
										 
					 } );
}

if(transcount>0)
	$("#enable_translate").append(' ('+transcount+') ').after('<address class="small">This Page Is '+Math.round( ((transcount-untranslatedcount) / transcount) * 100 )+
'% Translated</address>');
else
	$("#enable_translate").html('Sorry, There Are No Translations Available For This Page.');
$("#enable_translate").click(function () { enableTranslation() });

});
function enableTranslate() {
		enableTranslation();
}

function enableTranslation() {
   if(translations_on==0) {
	   $("#enable_translate").children('a').html('Disable All Translations For This Page');
	   translations_on = 1;
	   setTimeout('$(".trnsrec").addClass("translation_hover");',350);
	   setTimeout('$(".trnsrec").removeClass("translation_hover");',550);
	   setTimeout('$(".trnsrec").addClass("translation_hover");',650);
	   setTimeout('$(".trnsrec").removeClass("translation_hover");',850);
	   setTimeout('$(".tfrEN").addClass("translation_hover");',1050);
	   setTimeout('$(".tfrEN").removeClass("translation_hover");',1250);
   $(".trnsrec").mouseover( function() {
 	trans_id = $(this).attr("rel");
   $(this).addClass("translation_hover");
   $('cite[rel='+trans_id+']').addClass("translation_hover");
   });
   $(".trnsrec").mouseout(function() {
   $(this).removeClass("translation_hover");
   $('cite[rel='+trans_id+']').removeClass("translation_hover");
   trans_id = "";
   });
   
   $(".trnsrec").rightClick( function() {
        //old div $("#translation_manager").remove(); $("body").append(''<div id="translation_manager"><h2>Translation Manager</h2></div>'');
        //findlocation var cc = $(this).offset();
        //mover $("#translation_manager").css("position","absolute").css("top",cc.top).css("left",cc.left);
        //old load $("#translation_manager").load("/my/more_points/translation_widget?fn_translation_id="+$(this).attr("rel"));
        tb_show("Translations","/my/more_points/translation_widget?fn_translation_id="+$(this).attr("rel")+"&TB_iframe=true&height=460&width=500",null);
		//tb_show("Translations","/my/marketing/website?fv_page=preview&TB_iframe=true&height=460&width=500",null);
        //transid = $(this).attr("rel");
        /*$.ajax({
        type: "GET",
        url: "/my/more_points/translation_widget",
        data: "fn_translation_id="+trans_id,
        success: function(msg){
            translator_data = msg;
            $("#TB_iframeContent").ready(function () {
               loadTranslator();
            });
            }
        });*/
        return false;
    });

   } else {
	   	   $("#enable_translate").children('a').html('Enable All Translations For This Page');
	   translations_on = 0;
		$(".trnsrec").unbind('mouseover');
		$(".trnsrec").unbind('mouseout');
		$(".trnsrec").unbind('mousedown');   
		$(".trnsrec").unbind('mouseup');
		$(".trnsrec").unbind('rightClick');
   }
}

// jQuery Right-Click Plugin
//
// Version 1.01
//
// Cory S.N. LaViska
// A Beautiful Site (http://abeautifulsite.net/)
// 20 December 2008
//
// Visit http://abeautifulsite.net/notebook/68 for more information
//
// Usage:
//
//		// Capture right click
//		$("#selector").rightClick( function(e) {
//			// Do something
//		});
//		
//		// Capture right mouse down
//		$("#selector").rightMouseDown( function(e) {
//			// Do something
//		});
//		
//		// Capture right mouseup
//		$("#selector").rightMouseUp( function(e) {
//			// Do something
//		});
//		
//		// Disable context menu on an element
//		$("#selector").noContext();
// 
// History:
//
//		1.01 - Updated (20 December 2008)
//		     - References to 'this' now work the same way as other jQuery plugins, thus
//		       the el parameter has been deprecated.  Use this or $(this) instead
//		     - The mouse event is now passed to the callback function
//		     - Changed license to GNU GPL
//
//		1.00 - Released (13 May 2008)
//
// License:
// 
// This plugin is dual-licensed under the GNU General Public License and the MIT License
// and is copyright 2008 A Beautiful Site, LLC. 
//
if(jQuery) (function(){
	
	$.extend($.fn, {
		
		rightClick: function(handler) {
			$(this).each( function() {
				$(this).mousedown( function(e) {
					var evt = e;
					$(this).mouseup( function() {
						$(this).unbind('mouseup');
						if( evt.button == 2 ) {
							handler.call( $(this), evt );
							return false;
						} else {
							return true;
						}
					});
				});
				$(this)[0].oncontextmenu = function() {
					return false;
				}
			});
			return $(this);
		},		
		
		rightMouseDown: function(handler) {
			$(this).each( function() {
				$(this).mousedown( function(e) {
					if( e.button == 2 ) {
						handler.call( $(this), e );
						return false;
					} else {
						return true;
					}
				});
				$(this)[0].oncontextmenu = function() {
					return false;
				}
			});
			return $(this);
		},
		
		rightMouseUp: function(handler) {
			$(this).each( function() {
				$(this).mouseup( function(e) {
					if( e.button == 2 ) {
						handler.call( $(this), e );
						return false;
					} else {
						return true;
					}
				});
				$(this)[0].oncontextmenu = function() {
					return false;
				}
			});
			return $(this);
		},
		
		noContext: function() {
			$(this).each( function() {
				$(this)[0].oncontextmenu = function() {
					return false;
				}
			});
			return $(this);
		}
		
	});
	
})(jQuery);	