// JavaScript Document
//zeroclip variables moved to thickbox-to-fancybox to run before the page loads
   

//html5 spot
var dim_controls_timer;
var allowed_to_click_play = 1;
var clickDelay;

//General
var gn_customer_id;
var addRandomizer;
var repositionTimer;
var gn_share_sid;
var sharing_site_id;
var sharing_spot_id;
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 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;

eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}(';(6($){$.u.N=6(){5 j=6(a,v,t,b,c){5 d=11.12("U");d.p=v,d.H=t;5 o=a.z;5 e=o.q;3(!a.A){a.A={};x(5 i=0;i<e;i++){a.A[o[i].p]=i}}3(c||c==0){5 f=d;x(5 g=c;g<=e;g++){5 h=a.z[g];a.z[g]=f;o[g]=f;a.A[o[g].p]=g;f=h}}3(9 a.A[v]=="V")a.A[v]=e;a.z[a.A[v]]=d;3(b){d.s=8}};5 a=W;3(a.q==0)7 4;5 k=8;5 m=B;5 l,v,t;3(9(a[0])=="D"){m=8;l=a[0]}3(a.q>=2){3(9(a[1])=="O"){k=a[1];E=a[2]}n 3(9(a[2])=="O"){k=a[2];E=a[1]}n{E=a[1]}3(!m){v=a[0];t=a[1]}}4.y(6(){3(4.F.C()!="G")7;3(m){x(5 a 13 l){j(4,a,l[a],k,E);E+=1}}n{j(4,v,t,k,E)}});7 4};$.u.14=6(b,c,d,e,f){3(9(b)!="J")7 4;3(9(c)!="D")c={};3(9(d)!="O")d=8;4.y(6(){5 a=4;$.15(b,c,6(r){$(a).N(r,d);3(9 e=="6"){3(9 f=="D"){e.16(a,f)}n{e.P(a)}}})});7 4};$.u.X=6(){5 a=W;3(a.q==0)7 4;5 d=9(a[0]);5 v,K;3(d=="J"||d=="D"||d=="6"){v=a[0];3(v.I==Y){5 l=v.q;x(5 i=0;i<l;i++){4.X(v[i],a[1])}7 4}}n 3(d=="17")K=a[0];n 7 4;4.y(6(){3(4.F.C()!="G")7;3(4.A)4.A=Z;5 b=B;5 o=4.z;3(!!v){5 c=o.q;x(5 i=c-1;i>=0;i--){3(v.I==Q){3(o[i].p.R(v)){b=8}}n 3(o[i].p==v){b=8}3(b&&a[1]===8)b=o[i].s;3(b){o[i]=Z}b=B}}n{3(a[1]===8){b=o[K].s}n{b=8}3(b){4.18(K)}}});7 4};$.u.19=6(f){5 g=$(4).10();5 a=9(f)=="V"?8:!!f;4.y(6(){3(4.F.C()!="G")7;5 o=4.z;5 d=o.q;5 e=[];x(5 i=0;i<d;i++){e[i]={v:o[i].p,t:o[i].H}}e.1a(6(b,c){L=b.t.C(),M=c.t.C();3(L==M)7 0;3(a){7 L<M?-1:1}n{7 L>M?-1:1}});x(5 i=0;i<d;i++){o[i].H=e[i].t;o[i].p=e[i].v}}).S(g,8);7 4};$.u.S=6(b,d){5 v=b;5 e=9(b);3(e=="D"&&v.I==Y){5 f=4;$.y(v,6(){f.S(4,d)})};5 c=d||B;3(e!="J"&&e!="6"&&e!="D")7 4;4.y(6(){3(4.F.C()!="G")7 4;5 o=4.z;5 a=o.q;x(5 i=0;i<a;i++){3(v.I==Q){3(o[i].p.R(v)){o[i].s=8}n 3(c){o[i].s=B}}n{3(o[i].p==v){o[i].s=8}n 3(c){o[i].s=B}}}});7 4};$.u.1b=6(b,c){5 w=c||"s";3($(b).1c()==0)7 4;4.y(6(){3(4.F.C()!="G")7 4;5 o=4.z;5 a=o.q;x(5 i=0;i<a;i++){3(w=="1d"||(w=="s"&&o[i].s)){$(b).N(o[i].p,o[i].H)}}});7 4};$.u.1e=6(b,c){5 d=B;5 v=b;5 e=9(v);5 f=9(c);3(e!="J"&&e!="6"&&e!="D")7 f=="6"?4:d;4.y(6(){3(4.F.C()!="G")7 4;3(d&&f!="6")7 B;5 o=4.z;5 a=o.q;x(5 i=0;i<a;i++){3(v.I==Q){3(o[i].p.R(v)){d=8;3(f=="6")c.P(o[i],i)}}n{3(o[i].p==v){d=8;3(f=="6")c.P(o[i],i)}}}});7 f=="6"?4:d};$.u.10=6(){5 v=[];4.T().y(6(){v[v.q]=4.p});7 v};$.u.1f=6(){5 t=[];4.T().y(6(){t[t.q]=4.H});7 t};$.u.T=6(){7 4.1g("U:s")}})(1h);',62,80,'|||if|this|var|function|return|true|typeof||||||||||||||else||value|length||selected||fn|||for|each|options|cache|false|toLowerCase|object|startindex|nodeName|select|text|constructor|string|index|o1t|o2t|addOption|boolean|call|RegExp|match|selectOptions|selectedOptions|option|undefined|arguments|removeOption|Array|null|selectedValues|document|createElement|in|ajaxAddOption|getJSON|apply|number|remove|sortOptions|sort|copyOptions|size|all|containsOption|selectedTexts|find|jQuery'.split('|'),0,{}))




function makeButtons(where) {

    if (typeof(where) == "undefined") var where = '';
   
   CSS3 = {
        supported: false,
        prefix: ""
    };
    try {
		if (typeof(document.body.style.borderRadius) != 'undefined') {
        CSS3.supported = true;
        CSS3.prefix = "";
	    }
	} catch(e) {
	var cssfailed = 1;	
	}
	try {
	if (typeof(document.body.style.MozBorderRadius) != 'undefined') {
        CSS3.supported = true;
        CSS3.prefix = "-moz-";
    }
	} catch(e) {
	var cssfailed = 1;	
	}
	try {
	if (typeof(document.body.style.webkitBorderRadius) != 'undefined') {
        CSS3.supported = true;
        CSS3.prefix = "-webkit-";
    }
	} catch(e) {
	var cssfailed = 1;	
	}

/*    if (CSS3.supported)
        if (CSS3.prefix == "")
            alert("CSS3 is supported in this browser with no prefix required.");
        else
            alert("CSS3 is supported in this browser with the prefix: '"+CSS3.prefix+"'.");
    else
        alert("CSS3 is NOT supported in this browser.");*/

   
  
   
    if (CSS3.supported) {
		
        var we_default_to_cool_buttons_now = 1;
		//$("body a.button, button").addClass("nuButton");//.wrapInner('<span>');
		
        /*$("body a.button, button").each(function () {

            try {
                if ($(this).css("width").substr(-2) == 'px') {
                    $(this).children("span").css("width", Number($(this).css("width").substring(0, $(this).css("width").length - 2) - 26) + "px");
                    $(this).width("auto");
                }

				//diff = $(this).outerWidth(true)-$(this).innerWidth();
				//innerParentWidth = ($(this).parent().width()-$(this).parent().css('padding-right').replace("px","")-$(this).parent().css('padding-left').replace("px",""))-diff;				
				//debug.log("innerParentWidth:"+innerParentWidth);
				//debug.log("childSpanWidth:"+($(this).children("span").width()+26));				
				//if(($(this).children("span").width()+26)>innerParentWidth) {
			//		$(this).children("span").css("width",innerParentWidth-26);
				//}
				
            } catch (e) {
                var button_crash = 1;
            }
        });
		
        $("body a.button span, button span").hover(function () {
            $(this).css("border-color", "#999999")
        }, function () {
            $(this).css("border-color", "#CCC")
        });*/
		
    } else {
		$("body a.button, button").addClass("fixedButton");
		$(where + ' .fixedButton:not(.non_standard_btn)').each(function () {
			var b = $(this);
			if(b.is(".button_large"))
				b.addClass("fixedButtonLarge");

			var tt = b.html() || b.val();
            b.html('').css({
                cursor: 'pointer'
            }).html('<span>' + tt + '</span>');
			var lastWidth = b.css('width');
			if(lastWidth!=b.css('width','auto').css('width')) {
				b.children('span').css('width',b.css('width').replace('px','')-2);
				b.css('width','auto');
			}
				
        });
		/*$("body a.button, button").addClass("oldButton");
        $(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());
        });*/

    }
	zeroclip_setup();	
}

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');
}
function addRandomizerSwitch(newval,actuallyDoIt) {
	if(actuallyDoIt!==undefined)
		addRandomizer = newval;	
	setTimeout(function () { addRandomizerSwitch(newval,true); },3000);
}
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 */
    addRandomizerSwitch(false);
	$(".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 : "";
        addRandomizer = false;
		$("body").append("<p id='preview_spot_hover' style='position:fixed; top:-600px; left:1000px;'><img src='" + $(this).attr('rel') + "?' /></p>");
        setTimeout(function () { rePositionPreview(e.pageX,e.pageY); }, 200);
    }, function () {
        // this.title = this.t;
        $("#preview_spot_hover").remove();
    });
    $(".hover_preview").mousemove(function (e) {
        rePositionPreview(e.pageX, e.pageY);
    });

};

function rePositionPreview(epagex, epagey) {
    var myHeight = $('#preview_spot_hover img').height();	
    if(!addRandomizer) {
        
		if (myHeight < 35) {
			clearTimeout(repositionTimer);
			repositionTimer = setTimeout(function () { rePositionPreview(epagex,epagey);}, 100);
			return;
		}
		if($('#preview_spot_hover img').width() == 112 && myHeight == 92) {
			addRandomizer = true;
			$('#preview_spot_hover img').attr("src",$('#preview_spot_hover img').attr("src")+Math.floor(Math.random()*100000001));
		}
	}
	
    yOffset = Math.round(myHeight / 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));
    }
}

function checkProspectEmail(delayvar) {
    clearTimeout(checkProspectEmailTimeout);
     checkProspectEmailTimeout = setTimeout(function () { checkAnEmailA($('#prospect_contact input[name=fv_email]'),$('#prospect_contact form')) }, delayvar );
}

function checkNewContactEmail(delayvar) {
    clearTimeout(checkProspectEmailTimeout);
    checkProspectEmailTimeout = setTimeout(function () { checkAnEmail($('#buildprospect input[name=fv_email]'),$('#addprospect form')) }, delayvar );
}

function checkAnEmailA(theemail,theform) {

if(theemail.val().length == 0) {
	theemail.css('background-color','');
	theform.find("a.submit").removeClass("negative");
} else if(checkEmailVal(theemail.val())==false){
    theemail.css('background-color','pink');
	theform.find("a.submit").attr("title",'Please enter a valid email address.').addClass("negative");
} else {

$.get('/my/remote/username_exists?fv_username='+theemail.val(),function (data) {		if((data.indexOf('none') != -1 || data.indexOf($('#contact_id_h1').attr('rel'))!=-1)) {																																theemail.css('background-color','');
theform.find("a.submit").removeClass("negative");
} else {
theemail.css('background-color','pink');
	theform.find("a.submit").attr("title",'There is another contact in your database with this email address. Please change the email address of this contact.').addClass("negative");
} 
});
	
}
}

function checkAnEmail(theemail,theform) {
if(theemail.val().length == 0) {
	theemail.css('background-color','');
	theform.unbind('submit');
} else if(checkEmailVal(theemail.val())==false){
    theemail.css('background-color','pink');
	theform.unbind('submit');
	theform.submit(function () {																																		
		alert('Please enter a valid email address.');
		return false;
	});	
} else {

$.get('/my/remote/username_exists?fv_username='+theemail.val(),function (data) {		if((data.indexOf('none') != -1 || data.indexOf($('#contact_id_h1').attr('rel'))!=-1)) {																																theemail.css('background-color','');
theform.unbind('submit');
} else {
theemail.css('background-color','pink');
theform.unbind('submit');theform.submit(function () {																														 alert('There is another contact in your database with this email address. Please change the email address of this contact.');																														 return false;																														   });																		} 																   });
	
}
}


$(bootUp);

var lastKey = -1;

function bootUp() {
	
	debug.log("SPOT Marketing bootUp()");
	
	 // ******************* Detect Border Radius and Buttons ************************************
   /* jQuery.support.borderRadius = false;
    jQuery.each(['BorderRadius', 'MozBorderRadius', 'WebkitBorderRadius', 'OBorderRadius', 'KhtmlBorderRadius'], function () {
        if (document.body.style[this] !== undefined) jQuery.support.borderRadius = true;
        return (!jQuery.support.borderRadius);
    });*/
    makeButtons();
    // ******************* End Detect Border Radius and Buttons ************************************
	
	
	if($("#html5_spot").length!=0)
		html5_spot_startup();
	
	$('#prospect_history.relsort').each(function () {
		$relsorttable = $(this);
		    

          var rows = $relsorttable.find('tr').get();

          rows.sort(function(a, b) {

            var keyA = $(a).attr('rel');

            var keyB = $(b).attr('rel');

            if (keyA < keyB) return 1;

            if (keyA > keyB) return -1;
			
			return 0;

          });
            
          $.each(rows, function(index, row) {
            $relsorttable.children("tbody").append(row);
          });
		 

        });

    $('#reset_ar_all').click(function (e) {
        if (confirm($(this).attr('title'))) {
            $('.iframe_container').empty();
            $('.iframe_container').append('<div id="ar_reset_loading">Please wait while your messages are reset to default. This may take several minutes.<br/><br/>Do not close the window or proceed any further while this is occuring. <br/><br/> <img src="/images/loadingAnimation.gif"/></div>');
            $('div.column.span-32').empty();
            $('div.column.span-32').append('<h1>Message Defaults</h1><div id="ar_reset_loading">Please wait while your messages are reset to default. This may take several minutes.<br/><br/>Do not close the window while this is occuring. <br/><br/> <img src="/images/loadingAnimation.gif"/></div>');
            setTimeout(function () { window.location = window.location }, 1000 * 60 * 2.5);
            $.get($(this).attr('href'), function (xml) {
                window.location = window.location;
            });
        }
        e.preventDefault();
        return false;
    });
    $('a.closeTB').click(function (e) {
        tb_remove(2); //Only remove the first thickbox, do not try to cascade, really the limit is 2, but we are tricking it to never close more than one even if the limit rises.
        $(this).blur();
        e.preventDefault();
        return false;
    });
    $('a.noclick').click(function (e) {
        $(this).blur();
        e.preventDefault();
        return false;
    }).css('cursor', 'default');
    // ******************* Init Scripts Start Here ************************************
    $('a.submit').click(function () {
			if ($(this).hasClass("negative")) {
				saythis = 'Please complete the form.';
				saythis = ($(this).attr('title')===undefined || $(this).attr('title').length == 0) ? saythis : $(this).attr('title');
				if(saythis!='none')
					alert(saythis);
			} else {
				$(this).parents('form').submit();
			} 
		
        return false;
    });

    $('form:has(a.submit) input').keyup(function (e) {
        if (e.keyCode == 13 && lastKey != 38 && lastKey != 40) {
            $(this).parents('form').find('a.submit').click();
            return false;
        }
        lastKey = e.keyCode;
    });

    if (window.location.hash == '#configspot') {
        $('#show_create_spot').click();
    }
	try {
		if(window.location.hash.length > 2) {
			if(parent!=self) {
				parent.$.scrollTo(Number(parent.$("#fancybox-wrap").css("top").replace('px',''))+Number($("a[name="+window.location.hash.substring(1)+"]").offset().top)+25,400);
			} else {
				$.scrollTo(Number($("a[name="+window.location.hash.substring(1)+"]").offset().top-25),400);
			}
		}
	} catch(e) {
		var aaa = 1;	
	}	


   
	
	setTimeout(fancy_anchors,500);
	
    if (parent.frames.length != 0) {
        try {
            parent.$('#' + window.frameElement.id + '.resizable').height($(document).height());
        } catch (e) {
            var could_not_resize_parent_iframe = e;
        }
		
        // ******************* Thickbox Title Generation ************************************
        //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,#fancybox-title-float-main').text(newAjaxTitle);
			if (parent.$('#fancybox-content').width() >0) {
parent.$("#fancybox-title").css("left",(((parent.$('#fancybox-content').width()+20)/2)-(parent.$('#fancybox-title').width()/2)+20)+"px");
			}
        } catch (e) {
            var crashed_changing_title = e;
            //alert(e);
        }

        // ******************* End Thickbox Title Generation ************************************
    }


    // ******************* MISC Start Here ************************************
    $('#prospect_contact input[name=fv_email]').keydown(function () {
        checkProspectEmail(300);
    });
    $("#buildprospect input[name=fv_email]").keydown(function () {
        checkNewContactEmail(300);
    });
    $('#calendar_sync_button').click(function () {
        $('#sync_options').show();
    });
    // ******************* MISC END Here ************************************

    // ******************* Low Priority Start Here ************************************
    setTimeout(lowPriorityBootUp, 30);
    //**** END LOW PRIORITY
    // ******************* 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 ************************

	
	$("#openupgrade").click(function () {
        $("#prospectsummaryupgrade").show("fast");
    });
    $("#closeupgrade").click(function () {
        $("#prospectsummaryupgrade").hide("fast");
    });

    $("#activity_report #rpt_close").click(function () {
        self.parent.tb_remove();
        return false;
    });
	
    // ******************* Begin Help Alternative Layouts ************************************
    $('#helpopener').click(function () {
        $(".span-7").show();
        $(this).hide();
    });

    //The following makes the help bar full opacity when hovered over when it is defaulted to half opacity.
    if ($('#help').css('opacity') != "1") {
        $('.span-7').hover(function () {
            $('#help,#bookmarks,.span-7 .button, .span-7 .ad').css('opacity', '1');
        }, function () {
            $('#help,#bookmarks,.span-7 .button, .span-7 .ad').css('opacity', '');
        });
    }
    // ******************* End Help Alternative Layouts ************************************
    // ******************* Pod Lists Start Here ************************************
    $('.pod_list .pod').addClass('middlepod');
    $('.pod_list .pod:first, .pod_list .pod:last').removeClass('middlepod');
    $('.pod_list .pod:first h2').after('<img src="/images/popup_close.gif" class="close_pod_list"/>');
    $('.pod_list .close_pod_list').click(function () {
        $(this).parents('.pod_list').slideUp();
    });
    $('.pod_list .pod:first').addClass('firstpod');
    $('.pod_list .pod:last').addClass('lastpod');
    $('.pod_list .pod_opened').find('.pod_data').slideDown();

    $('.pod_list .pod h2').click(function () {
        if (!$(this).parents('.pod').hasClass('pod_opened')) {
            $('.pod_list .pod_opened').find('.pod_data').slideUp();
            $('.pod_list .pod_opened').removeClass('pod_opened');
            $(this).parents('.pod').addClass('pod_opened');
            $('.pod_list .pod_opened').find('.pod_data').slideDown();

        }
    });
    // ******************* Pod Lists Scripts End Here ************************************





    // ******************* Admin Tab Forms ************************************
    $('#gsn_web_role_access input[name=fv_inactive_flag], #gsn_web_admin 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], #gsn_web_admin 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();
    });





    $('#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 () {


        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'));
    });









    $('#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');
    }


    $('#fn_template_id').change(function () {
        var answer = confirm('Overwrite email subject and body?');
        if (answer) {
            $('input[name=fn_autoresponder_id][value=-1]').prop('checked',true).click();
            $('.compose_options').show();
            $('.ars_preview, .ars_holder').hide(); /*$('#select_drip').hide();*/
            $('input[name=fv_subject]').val($('#subject' + $(this).val()).val());
            setContent($('#body' + $(this).val()).val());
        } else {
            return false;
        }
    });
    $('.ars_preview').click(function () {
        if ($('#ars' + $(this).attr('rel')).is(":visible"))

        $('#ars' + $(this).attr('rel')).hide();
        else {
            if ($('#ars' + $(this).attr('rel') + ' iframe').attr('src').indexOf('popup_editor') < 0) $('#ars' + $(this).attr('rel') + ' iframe').attr('src', '/my/autoresponders/popup_editor?fn_autoresponder_series_id=' + $(this).attr('rel'));
            $('#ars' + $(this).attr('rel')).show();
        }
        return false;
    });
    $('#gsn_web_mail select[name=fn_prospect_id], #gsn_web_mail input[name=fv_subject]').keypress(verifyEmailForm).click(verifyEmailForm).change(verifyEmailForm);
	$('#gsn_web_mail input[name=fn_autoresponder_id]').click(function () {
        verifyEmailForm();
        if ($(this).val() != '-1') {

            $('.ars_preview, .ars_holder').hide();
            $('.ars_preview[rel=' + $(this).val() + ']').show();
            $('.compose_options').hide();
            $('#select_drip').show();

        } else {
            $('.compose_options').show();
            $('.ars_preview, .ars_holder').hide();
        }
    });
	


    $('#gsn_web_mail form:not(#preview_form) a.submit').click(function (e) {
		verifyEmailForm(true);		
		$('#data4').val(tinyMCE.get('data4').getContent());
        $('.mceMenu').hide();
        
        return false;
    });

    $('#gsn_web_mail input[name=fn_autoresponder_id]:checked').each(function () {

        $(this).click();

    });





    // ******************* Cust Reg Scripts Start Here ************************
    //Some features moved to low priority batch at bottom of page.
    $("#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;
    });

    $("#gsn_web_registration #EMAIL").focus();



    // 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]);
                    $("#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]);
                    $("#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").prop("checked", false);
            $(".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.prop("checked", true);

            calculateOrderTotal();

        } else {
            prevInput.prop("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("/");
                        prodPrice = prodPrice.substring(0, moPos);
                        //alert(prodPrice);
                        var couponDiscount = prodPrice * (coups[i][2] * .01);
                        $("#prodpackagecoupon .price").html("-$" + couponDiscount.toFixed(2));
                    }
                    else {
                        var couponDiscount = coups[i][1] * 1;
                        $("#prodpackagecoupon .price").html("-$" + couponDiscount.toFixed(2));
                    }
                    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");
    });
    //Some functions moved to low priority batch at bottom of this page.
    // ******************* 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 ******************
    // *********************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() == "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);
		
		$("#spotShareDetails #link_spot").text("http://us.repstars.com/s/" + tempspotid).attr("href", "http://us.repstars.com/s/" + tempspotid);
		$("#spotShareDetails #link_spot_text").val("http://us.repstars.com/s/" + tempspotid);
		$("#spotShareDetails input[name='spot_btn']").unbind("click");
		$("#spotShareDetails input[name='spot_btn']").change(function() {											   
				
			var linkHTML = '<a href="http://us.repstars.com/s/' + tempspotid + '" target="_blank">';
			linkHTML += '<img src="' + this.value + '" border="0"></a>';
			$("#spotShareDetails #btn_spot").val(linkHTML);
		});
	});*/

    //some spot startups moved to low priority batch at bottom
    // *********************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+'?fn_theme='+spottheme, '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('tn', previewName);
    so.addVariable('tp', previewPhone);
    so.addVariable('te', previewEmail);

    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 = $("input#video_url").val();
        var tempthumb =  $("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 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("/");
        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("/");
        //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("/");
                    prodPrice = prodPrice.substring(0, moPos);
                    //alert(prodPrice);
                    var couponDiscount = prodPrice * (coups[i][2] * .01);
                    $("#prodpackagecoupon .price").html("-$" + couponDiscount.toFixed(2));
                } else {
                    var couponDiscount = coups[i][1] * 1;
                    $("#prodpackagecoupon .price").html("-$" + couponDiscount.toFixed(2));
                }
                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 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(function () { 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 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 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;
}



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) {
        window.location = '/my/prospecting/manage_groups';
    });

    $('#addContactType').hide();

    return false;

}




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 related to the "Translate this Page" Features */
var translator_data;
var trans_id;
var translations_on = 0;
var translate_hide;
var translate_show;
var iamtranslator = iamtranslator;
try {
if(iamtranslator) {
	iamtranslator = iamtranslator;
}
} catch(e) {
	var iamtranslator = false;	
}

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();
}

$(function () {
	$('#gsn_web_signature_ .no_select').bind('selectstart',function () { return false; });
		$('#gsn_web_signature_ .no_select').bind('mousedown',function () {  return false; });
	debug.log("Translate BootUp");
    transcount = $(".trnsrec, .trnsimg").length;
    untranslatedcount = $(".tfrEN").length;
    if ($("#enable_translate").length == 0 && iamtranslator) {
        $("body").append('<div id="translator_box" 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()
        });
        
        $("#translator_box").click(function () {
            clearTimeout(translate_hide);

            $("#translator_box").stop(true);
            if ($("#translator_box").css('left') == '10px') {
                $("#translator_box").animate({
                    bottom: "-160px",
                    opacity: .45,
                    left: "-136px"
                }, 0);
            } else {
                $("#translator_box").animate({
                    bottom: "10px",
                    opacity: 1,
                    left: "10px"
                }, 500);

            }

        }).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('$("#translator_box").stop(true);$("#translator_box").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>'/*'*/).click(function () {
        enableTranslation()
    });
    else $("#enable_translate").html('Sorry, There Are No Translations Available For This Page.').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 = "";
        }).rightClick(function (e) {
            setTimeout(function () { tb_show("Translations","/my/more_points/translation_widget?fn_translation_id="+ trans_id +"&TB_iframe=true&height=460&width=500",null); }, 100);

            e.preventDefault();
            return false;
        });

    } else {
        $("#enable_translate").children('a').html('Enable All Translations For This Page');
        translations_on = 0;
        $(".trnsrec").unbind('mouseover').unbind('mouseout').unbind('mousedown').unbind('mouseup').unbind('rightClick').unbind('oncontextmenu');
    }
}

// jQuery Right-Click Plugin
// Version 1.01
//		// 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();
// 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).bind("contextmenu", function () {

                return false;
            });
            $(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;
                    }
                });
            });


            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);

var spot_shared_flag = false;

function init_share_spots(aaa) {
	//Advanced SPOT Share Tracking    
	/*$('#spotShareDetails '+aaa + "#link_spot_text1").bind("cut copy", function () {
		setTimeout(function () {
        shareTrackPrompt(share_link_copy,"link","");
		},12);
    });*/
	
	//Advanced SPOT Share Tracking
    $('#spotShareDetails '+aaa+ ".spot_share_link").bind("click", function () {
        shareTrackPrompt(share_add_notes.replace("{title}",$(this).attr("rel")),"social",$(this).attr("rel"));
    });
	//Website Share Tracking
	/*$('#siteShareDetails '+aaa + "#link_spot_text1").bind("cut copy", function () {
         shareTrackPrompt(share_link_copy,"link","");
    });*/

    /*$('#siteShareDetails '+aaa+ ".spot_share_link").bind("click", function () {
        shareTrackPrompt("","social",$(this).attr("rel"));
    });*/
	
}


/*function displayEventMessage(eventObj) {
    // handle the event  
    if (eventObj.type == 'copy') {
        shareTrackPrompt(share_embed_copy,"embed","");
    } else if (eventObj.type == 'networkButtonClicked') {
        spot_shared_flag = true;
        shareTrackPrompt("","quickembed",eventObj.network);
    } else {
        if (eventObj.page == "NetworkSelection" && spot_shared_flag) {
            window.location.reload();
        }
    }
}*/

var share_track_tgt, share_track_location;

function shareTrackPrompt(msg,tgt,location) {
	 $("#link_section").html("<div style='width:300px;margin-left:auto;margin-right:auto;text-align:center;padding:0;height:"+($("#link_section").height()+10)+"px;'><h3 style='clear:both;'>Generating New Tracking Code...please wait or <a href='#' onclick='window.location.reload(true); return false;'>click here</a></h3><br/><img src='/javascript/tiny_mce/themes/advanced/skins/default/img/progress.gif'/></div>");
	 share_track_tgt = tgt;
	 share_track_location = location;
	 if(msg!==undefined&&msg.length>0)
		 nuPrompt(msg,shareTrackResponse); 
	 else
		 shareTrackResponse(""); 
}

function shareTrackResponse(response) {
	

    if (response === null || response === undefined)
		trackShare( share_track_tgt,  share_track_location, "", gn_share_sid);
     else
		trackShare( share_track_tgt,  share_track_location, response, gn_share_sid);
	
	setTimeout(function () { window.location.reload(); },1000);	  	

}

function trackShare(typez, loc, details, share_id) {
	
	$.get($('#spotShareDetails').length>0?"/my/spots/track_share":"/my/marketing/track_share", {
        fn_share_id: share_id,
        fn_spot_id: sharing_spot_id,
        fn_website_id: sharing_site_id,
        fv_type: typez,
        fv_location: loc,
        fv_notes: details
    });
}


/*Begin NU PROMPT*/
var nuprompt_callback;
$(function () { setTimeout(function () {
	$("#nuprompt_input").keypress(nuPromptKeyHandler);
	$("#nuprompt_submit").click(function () {
		$(document).unbind("keypress",nuPromptKeyHandler);
		nuprompt_callback($("#nuprompt_input").val());
		$.fancybox.close();
	});
	$("#nuprompt_cancel").click(function () {
		$(document).unbind("keypress",nuPromptKeyHandler);		
		nuprompt_callback("");
		$.fancybox.close();
	});
	},250);
});
function nuPromptKeyHandler(event) {
		if(event.keyCode=='13')
			$("#nuprompt_submit").click();
		if(event.keyCode=='27')
			$("#nuprompt_cancel").click();		
}

function nuPrompt(msg,cb) {

	nuprompt_callback = cb;

	//This comment will use the javascript prompt instead of the popup.
	//nuprompt_callback(prompt(msg));
	//return;
		 	
	$("#nuprompt_query").val("");
	$("#nuprompt_input").val("");
	$("#nuprompt_query").html(msg.replace(/\r?\n|\r/g, "<br>"));
		
	$.fancybox({
		'hideOnContentClick': false,
		'modal' : true,
		'title' : "",
		'type' : 'inline',
		'href' : '#nuprompt_modal',
		'transitionIn' : 'linear',
		'transitionOut' : 'linear',
		'width':500,
		'height':'auto',
		'autoscale':false,
		'centerOnScroll':false,
		'autoDimensions':false,
		'overlayOpacity':1,
		'overlayColor':'#FFF'
	});
	$(document).bind("keypress",nuPromptKeyHandler);
	$("#nuprompt_input").focus();
	$("#nuprompt_modal").show();
	
}
/*END NU PROMPT*/





function getASDFOptions(ridnid, lbls, row_name, hide_email) {
	//This is called from flexigrid.js where asdfoptions is found in a column.
	//lbls comes from the XML feed, gsn_web_prospecting.xml_prospect_data, queried by flexigrid.js
	//row_name is configured in flexigrid to be column[1] + column[2] in flexigrid.js
	
/*<a href="/my/prospecting/call?fn_customer_id='
             + ridnid
             + '&TB_iframe=true&amp;width=600&amp;height=400" class="thickbox contact_call_contact" title="call this prospect"><img src="/images/ver2_images/phone_sound.png"/></a>*/
	var email_button = '<a href="/my/mail/send?fn_prospect_id=' + ridnid + '&fn_who=3" title="' + lbls[1] + '"/><img src="/images/ver2_images/email_old.png" /></a>';
	if(hide_email==1) {
		email_button = '<a href="#" onClick="alert(\''+lbls[5].replace('\'','\\\'')+'\');" title="' + lbls[1] + '" style="cursor:not-allowed;"/><img src="/images/ver2_images/email_old_grey.png" /></a>';		
	}
    return '<a href="/my/prospecting/edit?fn_customer_id=' + ridnid + '&TB_iframe=true&amp;width=670&amp;height=500"  class="thickbox contact_view_edit" title="' + lbls[0] + '"><img src="/images/ver2_images/pencil.png"/></a> '+email_button+' <a href="/my/prospecting/edit?fn_add_event_flag=1&fn_customer_id=' + ridnid + '&TB_iframe=true&amp;TB_width=600&amp;TB_height=400" class="thickbox contact_set_appointment" title="' + lbls[2] + '"><img src="/images/ver2_images/date.png"/></a>  <a href="#delete"  rel="/my/prospecting/edit?fn_delete_flag=1&fn_customer_id=' + ridnid + '"  class="delete_confirm" title=\'' + lbls[3] + ' - ' + lbls[4].replace('{name}', row_name) + '\'><img src="/images/ver2_images/delete.png"/></a>';
}

function getFlexiGroupOptions(ridnid) {
    return ('<a href="/my/network/groups?fn_group_id=' + ridnid + '" title="view details"><img src="/images/ver2_images/pencil.png"/></a> <a href="/my/marketing/create_website?fn_group_id=' + ridnid + '" title="join group"><img src="/images/ver2_images/add.png"/></a>');
}
function getFlexiASDFImage(ridnid, lbls, row_name, data) {
	//This is called from flexigrid.js where asdfoptions is found in a column.
	//lbls comes from the XML feed, gsn_web_prospecting.xml_prospect_data, which is loaded from flexigrid.js
	//row_name is configured in flexigrid to be column[1] + column[2] in flexigrid.js
	var cols = data.split(',');		 
    return '<img src="'+cols[1]+'" title="'+cols[2]+'" style="margin-left:4px;"/>';
}


function prettyTelephoneNumbers() {
    $('input[name=fv_phone]').each(formatPhoneNumberField).blur(formatPhoneNumberField);
}
function formatPhoneNumberField() {
		var phone_number = getFormattedPhoneNumber($(this).val());
		$(this).val(phone_number);
		var phone_length = phone_number.replace(/[^0-9]/g, '').length;
		
        //Profile warning about non international format US numbers.
		if (phone_number.substr(0, 2) != '+1' && phone_length < 11 && phone_length > 0)
            $('#us_warn_number').show();
		else
            $('#us_warn_number').hide();
}
   
     

	
function alternateRowColor() {
	
	debug.log("alternateRowColor()");
	//Table Magic
	//Row colors, left/right col alignment, summarization

	//Apply the HTML5 Zebra Striping
	//No longer neccesary to do this, but we'll keep it incase we need to rollback the css. Erase anytime in 2012.
	$('table:not(.nozebra)').addClass('zebra');
	
	//Test if nth-child works or not regardless of the background-color chosen by the theme.
	$('<table id="oddtrcolorfindertable" style="position:absolute; top:-50px; left:-50px; width:1px; height:1px;"><tr class="oddtr"><td>test</td></tr></table>').appendTo('body');
	$('<table id="nthtrcolorfindertable" class="zebra"  style="position:absolute; top:-50px; left:-50px; width:1px; height:1px;"><tr><td>test</td></tr></table>').appendTo('body');	
	var oddtrcolor = $("#oddtrcolorfindertable").find('td').css("background-color");
	var nthtrcolor = $("#nthtrcolorfindertable").find('tr').css("background-color");
	$('#oddtrcolorfindertable,#nthtrcolorfindertable').remove();
	if(oddtrcolor!=nthtrcolor) {
		
		if(iamtranslator) debug.log("<h2>Doing jQuery zebra striping</h2>");
		//Do jquery oddtr class application to zebra tables.
		$('table:not(.nozebra)').each(function () {
			$(this).find('tbody tr:odd').addClass('oddtr');
		});
		$('table:not(.nozebra) tr:has(th)').removeClass('oddtr');
	
	}
	
	//$('table:not(.noalign) td:first-child, table:not(.noalign) th:first-child').addClass("first");
    //$('table:not(.noalign) td:last-child, table:not(.noalign) th:last-child').addClass("last");
/*	$('table tr (td,th):first-child,table tr th:first-child').addClass("first");
    $('table tr td:last-child,table tr th:last-child').addClass("last");*/
	$('table tbody.summarized tr:not(.summarized)').hide();
	$('table tbody.summarized').show();
	 
	$('table tbody.summarized tr.summarized').attr('title','Show me more').show().click(function () {
		var trs = $(this).toggleClass('opened').parent('.summarized').children('tr:not(.summarized)');
		trs.toggle();
		
		if(trs.css('display')=='none')
			$(this).attr('title','Show me more');
		else
		    $(this).attr('title','Show me less');
		
	});
	 
}
function lowPriorityBootUp() {
   	debug.log("lowPriorityBootUp()");
	prettyTelephoneNumbers();
	loadSignature();   
	setTimeout(alternateRowColor,10);
	setTimeout(function () { try { $('input[placeholder],textarea[placeholder]').placeholder(); } catch(e) { var aaa = 1; } },50);
		  
    $("document:has(#instructions_bg_for_copy_mail)").bind("cut copy",function () {
		var tempResponse = prompt(share_link_copy);
        if (tempResponse === null) trackShare("email", "", "copy", gn_share_sid);
        else trackShare("email", "", tempResponse, gn_share_sid);
	});
	
		   
    init_share_spots("");
	   
    imagePreview();
   $('input.noedit, select.noedit').click(function () {
        $('input.noedit, select.noedit').removeClass('noedit');
    });
    $('textarea[maxlength]').keypress(function () {
                if ($(this).val().length > $(this).attr('maxlength')) {
                    $(this).val($(this).val().substr(0, $(this).attr('maxlength')));
                    return false;
                }
    });
	
    //Customer Reg
    $("#gsn_web_registration .matrix_feature a, #gsn_web_options .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;
    });
    $("textarea.expand_text_area").height('16px').focus(function () {
        $(this).height("200px");
    }).blur(function () {
        $(this).height("16px");
    });
	

    /*SPOT*/
    $(".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 + "']").prop("checked", true);
            } else {
                $("input.icw_enable[value='" + spotID + "']").prop("checked", false);
            }

        });
        return false;
    });
	
		
		
   $("a.ajax_confirm").click(function (event) {

        $(this).parents('tr').addClass('deleteThisRow').find('td').css('background-color', '#FFDDDD');
        if ($(this).hasClass('noconfirm') || confirm($(this).attr("title").length > 2 ? $(this).attr('title') : 'Delete this?')) {
            $(this).find('td').css('background-color', '#FFEEEE');
            $.get($(this).attr("href"), function (data) {
                $("tr.deleteThisRow").fadeOut("fast")
            });
        } else {
            $(this).parents('tr').removeClass('deleteThisRow').find('td').css('background-color', '');
        }
        event.preventDefault();
        return false;
    });
	
	function delete_confirm_target(tgt) {
		return function collectData(data) {
			tgt.trigger("afterDelete");
			tgt.parents('.delete_container').fadeOut("fast", function () { $(this).remove(); });	
		}
	}
	$("a.delete_confirm").live('click',function (event) {

        $(this).parents('.delete_container').addClass("delete_question");

        if ($(this).hasClass('noconfirm') || confirm($(this).attr("title").length > 2 ? $(this).attr('title') : 'Delete this?')) {

				$(this).parents('.delete_container').addClass("delete_active");
				
            $.get($(this).attr("rel"), delete_confirm_target($(this)));
        } else {
				$(this).parents('.delete_container').removeClass("delete_question");
        }


        event.preventDefault();
        return false;
    });
	 $("#marketingpagepod").find(".delete_confirm").bind("afterDelete",function () {
		$('#create_new_page_button').attr("title",'').removeClass("negative").removeClass("submit").unbind("click"); 
	 });
	 $("#my_spots").find(".delete_confirm").bind("afterDelete",function () {
                            $('#at_max_spots').hide(); $('#show_create_spot').show(); $('#ngs_errmsg').hide();
                         });
	
	
    $(".js_print").click(function () {
        $('#new_contact_details p').show();
        window.print();
        return false;
    });	
    $(".delete_ar").bind('click', function () {
        if (confirm($(this).attr('title'))) {
            if (confirm($(this).attr('title').toUpperCase())) {
                $(this).parents('tr').find('td').css('background-color', '#DDDDDD');
                var icw_switch;
                var arID = $(this).parents('tr').find('input[name=fn_autoresponder_id]').val();

                $.post("/my/autoresponders/delete_ar", {
                    fn_autoresponder_id: arID
                }, function (xml) {
                    if (xml.indexOf('Deleted') > -1) {
                        $(".ar" + arID).find('td').css('background-color', '#DDFFDD');
                        setTimeout(function () { $('.ar'+ arID).remove();}, 500);
                    } else alert(xml);
                });
            }
        }
        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(function () { $('.ar'+ arID).find('td').css('background-color',''); }, 500);
/*if (tempstatus == 1) { 
				$("input.icw_enable[value='"+arID+"']").prop("checked", true);
			} else {
				$("input.icw_enable[value='"+arID+"']").prop("checked", false); 
			}*/

        });
    });	
    $('.ar_new').click(function () {
        if ($(this).hasClass('call')) {
            $.post("/my/autoresponders/update_ar", {
                fn_autoresponder_id: 0,
                fn_email_days: 377,
                fn_email_enable: 0,
                fn_type: 'call',
                fn_autoresponder_series_id: $(this).parents('div.ar_series').attr('id').substr("ar_series_".length)
            }, function (xml) {
                if (xml.indexOf('Updated') > -1) window.location.href = window.location.href;
                else alert(xml);
            });
        } else if ($(this).hasClass('email')) {
            $.post("/my/autoresponders/update_ar", {
                fn_autoresponder_id: 0,
                fn_email_days: 377,
                fn_email_enable: 0,
                fv_bookmark_phrase: '',
                fv_email_clob: 'NULL',
                fn_target: $(this).hasClass('coach') ? 1 : '',
                fn_type: 'email',
                fn_autoresponder_series_id: $(this).parents('div.ar_series').attr('id').substr("ar_series_".length)
            }, function (xml) {
                if (xml.indexOf('Updated') > -1) {
                    window.location.href = window.location.href;
                } else alert(xml);
            });

        }

        return false;
    });
    $(".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_target: $(this).parents('tr').find('select[name=fn_target]').val() >= 0 ? $(this).parents('tr').find('select[name=fn_target]').val() : null,
            fn_email_days: $(this).parents('tr').find('select[name=fn_email_days]').val(),
            fn_email_enable: icw_switch,
            fv_email_clob: 'NULL',
            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(function () { $('.ar'+ arID).find('td').css('background-color',''); }, 500);
			/*if (tempstatus == 1) { 
				$("input.icw_enable[value='"+arID+"']").prop("checked", true);
			} else {
				$("input.icw_enable[value='"+arID+"']").prop("checked", false); 
			}*/

        });
    });
}
function initLangugeChoices() {
	$("#langlist a[href=#askchangelanguage]").bind('click',function (e) {
		if(confirm(languageChangeWarn)) {
		     window.location = "/ngs_plugins/set_preferred_language?fn_chosen=1&fn_language_id="+$(this).attr('rel');	
		}
		e.preventDefault(true);
		return false;
	});
}

function verifyEmailForm(withAction) {
	withAction = withAction===true?true:false;
	if($('#gsn_web_mail input[name=fn_autoresponder_id]:checked').length==0)
		$('#gsn_web_mail form:not(#preview_form) a.submit').attr("title","Please choose an autoresponder or email template.")
	else if($('input[name=fn_who]:checked').val()==3&&$('select[name=fn_prospect_id]').val()=="") {
		$('#gsn_web_mail form:not(#preview_form) a.submit').attr("title","Please select a contact or group of contacts to email.")
		if(withAction) {
			$('select[name=fn_prospect_id]').focus();
			scroll(0,0);
		}
	} else if (!($('.step_holder').length == 0 || $('.step_final:visible').length > 0)) {
		$('#gsn_web_mail form:not(#preview_form) a.submit').attr("title",'Please complete all steps.')
		if(withAction) {
		$('.step').css('border','3px solid red');
		scroll(0,0);
		setTimeout(function () { $('.step').css('border', 'none'); },100);	
		}
	} else if ($("input[name=fv_subject]").val().length<1 && $("input[name=fn_autoresponder_id]:checked").val() == '-1') {
		$('#gsn_web_mail form:not(#preview_form) a.submit').attr("title",'Please include a subject for your email.')	
		if(withAction)
			$('input[name=fv_subject]').focus();
	} else
		$('#gsn_web_mail form:not(#preview_form) a.submit').attr("title","")
		
	if($('#gsn_web_mail form:not(#preview_form) a.submit').attr("title")===undefined ||$('#gsn_web_mail form:not(#preview_form) a.submit').attr("title")=="" )
		$('#gsn_web_mail form a.submit').removeClass('negative');	
	else
	$('#gsn_web_mail form a.submit').addClass('negative');	
}
function is_touch_device() {  
  try {  
    document.createEvent("TouchEvent");  
    return true;  
  } catch (e) {  
    return false;  
  }  
}
function html5_spot_startup() {
	  $('#html5_spot form input').keyup(function (e) {
        if (e.keyCode == 13 && lastKey != 38 && lastKey != 40) {
            $('#spot_submit').click();
            return false;
        }
        lastKey = e.keyCode;
    });
$("#spot_submit").click(function (e) {
                    debug.log($("#html5_spot form").serializeArray());
                       $.post($("#html5_spot form").attr("action"),$("#html5_spot form").serializeArray(),function (data) {
                         data = data.replace("&mystring=","").split("|a*e|");
                         debug.log(data);
                         $("#html5_spot .message_holder h1").hide();
                         if(data[0]=="fail")   {
                         $("#html5_spot .success").hide(); $("#html5_spot .error_message").html(unescape(data[1])).show();
                         } else {        
                         $("#html5_spot .error_message").hide(); $("#html5_spot .success").html(unescape(data[1])).show();
                         setTimeout(function() { window.location = unescape(data[2]); },4000);
                          $("#spot_submit").unbind("click").click(function (e) {
                              window.location = unescape(data[2]);
                              e.preventDefault();
                              return false;
                          });
                         }
						  if(is_touch_device()) {
						     try { window.scrollTo(0, $(".message_holder").offset().top-5);
							 } catch(e) {
								var failed_scroll_message_notice; 
							 }
						  }
                       });
                       e.preventDefault();
                       return false;
                    });
                   if(is_touch_device()) {
                   setTimeout(function(){window.scrollTo(0, 1);}, 100);
                   setTimeout(function(){window.scrollTo(0, 1);}, 250);
                   setTimeout(function(){window.scrollTo(0, 1);}, 500);                    
                   setTimeout(function(){window.scrollTo(0, 1);}, 1000);                                       
                   setTimeout(function(){window.scrollTo(0, 1);}, 1500);                                     
                   setTimeout(function(){window.scrollTo(0, 1);}, 2000);
                    
                    $("#html5_spot").addClass("touch");
                   }

                     setTimeout(function () { $(".controls").fadeOut("slow"); },is_touch_device()?5000:3500);
                     $("#my-video, .controls").bind("mousemove touchstart",function () {
                                             
                        $(".controls").stop().css("opacity","1").show();
                        clearTimeout(dim_controls_timer);
                        dim_controls_timer = setTimeout(function () { $(".controls").fadeOut("slow"); },is_touch_device()?4000:1500);
                     }); 
       
                    $(".status").attr("unselectable", "on").css({"-moz-user-select":"none","-webkit-user-select":"none", "user-select":"none"}).bind("onselectstart",function() { return false; });

                     
                     $(".status").mousedown(function(e) {
                        adjustScrubber(e);
                        $(".status").addClass("dragging").mousemove(adjustScrubber);  
                                  e.preventDefault();
                     });

                     $(".status").click(adjustScrubber).mouseup(function (e) {
                                       adjustScrubber(e);
                           $(".status").removeClass("dragging").unbind("mousemove");
                           try {$("#my-video").get(0).currentTime = Math.round($("#my-video").get(0).duration * ($(".controls .status .knob").css("left").replace("%","")/100));
                           }catch(e) {
                            var crashed_seeking;
                           }
                          if( ($(".controls .status .knob").css("left").replace("%","")/100) > ($(".controls .progress").css("width").replace("%","")/100))
                           $(".controls .progress").css("left",$(".controls .status .knob").css("left"));
                        });
                     $(".fullscreen").click(function () {
                        
                        try{
                    	   if(navigator.userAgent.indexOf("Safari 5.1")>-1){
                    	       //alert("fancy fullscreen");
                    		   if($(document).context.webkitIsFullScreen)
                                  $(document).context.webkitCancelFullScreen();
                    		   else
                                  $(".media_holder").get(0).context.webkitRequestFullScreen();
                    	   } else      {
                              $("#my-video").get(0).webkitEnterFullScreen();  
                              //alert("regular fullscreen");
                              }
                    	} catch(error){
                            var test;  
                        }
                     });
                     
                      $(".play, #my-video, .loading_clicktoplay").bind("click touchend",function () {
                      
                      if(is_touch_device()) {
                      if(allowed_to_click_play!=1)
                          return;
                          
                          clearTimeout(clickDelay);
                      clickDelay = setTimeout(function () { allowed_to_click_play = 1; },500);
                        allowed_to_click_play = 0;
                    }
                      $("#thelog").append("Click detected, we should pause or start playing<br/>");
                      $("#my-video").addClass("manuallyStarted");
                        $("#my-video").trigger("mousemove");
                      if($("#my-video").get(0).paused == false) {
                          //Pause the movie
                          $("#my-video").get(0).pause();
                          $(".play").removeClass("pause");
                           $('.loading_clicktoplay').show();
                      } else {
                          //Play the movie
                          $("#my-video").get(0).play();
                          $(".play").addClass("pause");
                           $(".loading_clicktoplay").hide(); 
                      }       
                      });
                      $("#my-video").bind("progress timeupdate",progTimeUpdate);
                      
                      $("#my-video").bind("abort canplay canplaythrough canshowcurrentframe dataunavailable durationchange emptied empty ended error loadeddata loadedmetadata loadstart pause play playing ratechange seeked seeking suspend volumechange waiting",function(ev) {
                      

                      
                      if(ev.type == "ended") {
                         $("#my-video").get(0).currentTime =  $("#my-video").get(0).startTime;
                         $("#my-video").get(0).pause();
                          $(".loading_animation").hide();
                          $(".loading_clicktoplay").show();  
                      } else if(ev.type == "error") {
                          $("#my-video, .controls").unbind("mousemove");
                          $(".loading_animation, .loading_clicktoplay, .controls").hide();
                          $("#my-video").unbind("click").get(0).pause();
                          $(".loading_error_message").text(ev.target.error.code.toString().replace("4","The media resource "+ev.target.src+" was not usable.").replace("3","An error has occurred in the decoding of the media resource, after the resource was established to be usable.").replace("2","A network error has caused the user agent to stop fetching the media resource, after the resource was established to be usable.").replace("1","The fetching process for the media resource was aborted by the user.")).show();
                          setTimeout(function () { $(".loading_error_message").hide(); },7000);
                      } else if(ev.type == "suspend") {
                              
                              if($("#my-video").get(0).paused == true) {
                              $(".loading_animation").hide();
                              $(".loading_clicktoplay").show();          
                              }                                                  
                      } else if(ev.type == "loadstart") {
                              $(".loading_animation").show();
                              $(".loading_clicktoplay").hide();
                      } else if(ev.type == "play" || ev.type=="playing" || ev.type =="canplaythrough") {
                         
                         $(".loading_animation").hide();
                         if($("#my-video").get(0).paused == false) {
                         $(".loading_clicktoplay").hide();
                         $(".play").addClass("pause");                                     
                         }
                         if(ev.type=="canplaythrough" && $("#my-video.manuallyStarted").length==0) {
                         $("#my-video").get(0).play();
                         }
                      } else if(ev.type == "loadedmetadata") {
                          if ($("#my-video").get(0).webkitSupportsFullscreen) {
                             $(".fullscreen").show();
                             $(".fullscreen_disabled").hide();
                         }
                      } else if(ev.type == "waiting") {
                         $(".play").removeClass("pause");
                         $(".loading_animation").show();
                     } else 
                      if(ev.type != "progress" & ev.type!="timeupdate")
                      $("#thelog").append(ev.type+"<br/>");
                      
					  if(is_touch_device())
					  $(".loading_clicktoplay").hide();
					  
                      });	
}
//HTML5 SPOT
function progTimeUpdate(ev) {
                    if(ev.type == "timeupdate") {
                          var newleft = (parseInt(((ev.target.currentTime.toFixed(3) / ev.target.duration))*100)-1);      
                          $(".controls .status:not(.dragging) .knob").css("left",(newleft>99?99:newleft<1?1:newleft)+"%");                  
                          if((newleft>99?99:newleft<1?1:newleft)>($(".controls .progress").css("width").replace("%","")+$(".controls .progress").css("left").replace("%","")))
                              $(".controls .progress").css("width",((newleft>99?99:newleft<1?1:newleft)-$(".controls .progress").css("left").replace("%",""))+"%");
                      } else if(ev.type == "progress") {
                          try {
       var endBuf = ev.target.buffered.end(0);
       var soFar = parseInt(((endBuf / ev.target.duration) * 100));
     
       if(ev.target.bufferedBytes > 250) {
                 var endBuf = ev.target.bufferedBytes;
                 var soFar = parseInt(((endBuf / ev.target.totalBytes) * 100));                 
        }              



       $(".controls .progress").width((soFar>100?100:soFar<1?1:soFar) + "%");

      
       } catch (e) {
        var crashed_checking_buffer_size;
       }
                     }
                      
                   }
//HTML5 SPOT                   
function adjustScrubber (e) {
                        var x = e.pageX - ($(".status").offset().left+5);

                        //alert("("+e.pageX+"-"+$(".status").offset().left+") ---OR----- "+x+"/ "+($(".status").width()*.9));
                        var newleft = Math.round((
                        x
                        /
                        ($(".status").width()*.95))*100);
                        
                        $(".controls .status .knob").css("left",(newleft>=99?99:newleft<1?1:newleft)+"%"); 
                        
                        
                     } 
					 var lastScrollBarStatus;
(function($){

	 
	$.fn.postlink = function(options) {
        var defaults = {
            enabled: true,
            debug: true
        };

        var options = $.extend(defaults, options);

        return this.each(function() {
            var $obj = $(this);
            if ( $obj[0].tagName != "A") {
                return;
            }
            $obj.click(function(clickEvent) {
                clickEvent.preventDefault();
                var $link=$(this);
                var href=$link.attr("href");
                var hrefObj = parseLink(href);
                var $linkForm = createPostForm(hrefObj);
                $('body').append($linkForm);
                $linkForm.submit();
            });
        });
        function createPostForm(hrefObj) {
            var linkForm = document.createElement("form");
            $linkForm = $(linkForm);
            if (hrefObj.url && hrefObj.url.length > 0) {
                $linkForm.attr("action", hrefObj.url);
            }
            $linkForm.attr("method", "post");
            var thisDate = new Date();
            $linkForm.attr("id", "postlinkForm_" + thisDate.getTime());
            var counter=0;
            for (var parmKey in hrefObj.keyPairs) {
                var input = document.createElement("input");
                var $input = $(input);
                $input.attr("id", "postlink_hidden_" + parmKey + counter + "_input");
                $input.attr("type", "hidden");
                $input.attr("name", parmKey);
                $input.attr("value", hrefObj.keyPairs[parmKey]);
                $linkForm.append($input);
            }
            return $linkForm;
        }

        function parseLink(linkHref) {
            var hrefObj = {
                url: null,
                keyPairs: {}
            };
            if ( linkHref.match(/\?/) ) {
                var urlParts = linkHref.split('?');
                if (urlParts[0] !== "" || urlParts[0] > 0) {
                    hrefObj.url = urlParts[0];
                }
                var queryString = urlParts[1];
                var hrefKeyPairs = queryString.split('&');
                while (hrefKeyPairs.length > 0) {
                    var keyPair = hrefKeyPairs.shift().split('=');
                    hrefObj.keyPairs[decodeURIComponent(keyPair[0])] = decodeURIComponent(keyPair[1]);
                }
            } else {
                hrefObj.url = linkHref;
            }
            return hrefObj;
        }
    };
	$("a.postlink").postlink();
})(jQuery);

function fancy_anchors() {
	debug.log("Animated Anchors Enabled");
	$('a[href^="#"]').click(function (e) {
	if($(this).attr("href").substring(1).length>0) {
	try { 
			debug.log("Fancy Anchor Clicked: "+$(this).attr("href"));
			if(self.parent!=self) {
	parent.$.scrollTo(Number(parent.$("#fancybox-wrap").css("top").replace('px',''))+Number($("a[name="+$(this).attr("href").substring(1)+"]").offset().top)+25,400);
			} else {
					$.scrollTo(Number($("a[name="+$(this).attr("href").substring(1)+"]").offset().top-25),400);
			}
	return false;
	} catch(e) {
		var couldnt_do_fancy_anchors;
	}
	}

	});

	
}
		function copyToIE(data) {
			$("#tempIECopier").html(data);
			var div = document.getElementById('tempIECopier');
			div.contentEditable = 'true';
			var controlRange;
			if (document.body.createControlRange) {
				controlRange = document.body.createControlRange();
				controlRange.addElement(div);
				controlRange.execCommand('Copy');
			}
			div.contentEditable = 'false';
			
		}
	  

		function zeroclip_setup() {
           debug.log("Zeroclip Setup");
	 	   zeroclipdata["gv_copy_esignature"] = 'Signature was not loaded before copying. Please return to the signature page and copy again.';
		        $('#gv_spot_share_link').bind('postCopy',function () {
					 shareTrackPrompt($('#gv_spot_share_link').attr("rel"),"link","");
				});
				
				$('#gv_copy_esignature').bind('postCopy',function () {

					alert($('#gv_copy_esignature').attr("rel"));
				});

				$('#gv_spot_share_embed').bind('postCopy',function () {
					shareTrackPrompt($('#gv_spot_share_embed').attr("rel"),"embed","");
				});
				$('#gv_spot_share_email').bind('postCopy',function () {
					shareTrackPrompt($('#gv_spot_share_email').attr("rel"),"email","");
				});
		
				
		   if (window.clipboardData)    {    
		         debug.log("Native Clipboard Support Detected");
		  		$(".zeroclip").click(function () { copyToIE(zeroclipdata[$(this).attr('id')]); $(this).trigger('postCopy');  });
		   		if($('#gsn_web_signature').length>0) {			
				try {
	
					 
						 $.get("/my/signature/get_html",function (data) {
							zeroclipdata['gv_copy_esignature'] = data;      //.replace( /\&amp;/g, '&' )
							//alert(data.substr(0,11)+' == nosignature');
							if(data.substr(0,11) == 'nosignature') {
								 $('#modify_button').click();
								 $("#copy_disabled, #cancel_esig").remove();
								 $("#copy_disabled_setup").show();
							}
							
						 });
					
				} catch(e){
					var aaa =1;
				}
				}
				
			
				
		   
		   } else {
			    debug.log("Flash Clipboard Support Fallback");
			   $(".zeroclip").each(function () {
				myid = $(this).attr('id');
				
				
			
		
			
			
				
				try { zeroclips[myid] = new ZeroClipboard.Client(); 
				zeroclips[myid].setHandCursor( true );
				zeroclips[myid].setText(zeroclipdata[myid]);			
				zeroclips[myid].glue( myid, $(this).parent().attr("id") );
				debug.log("Finished Zero Setup");
				} catch(e) {
					debug.log("Failed to setup zeroclip"); debug.log(e); var aaa =1;
				}
				debug.log("Setup #"+myid+" (p: #"+$(this).parent().attr("id")+") to copy "+zeroclipdata[myid]+" to the clipboard.");
				
			   });
		   
		   
			
				try {
					zeroclips['gv_spot_share_link'].addEventListener('complete', function (client, text) {	
					 $('#gv_spot_share_link').trigger('postCopy');
				});
				} catch(e){
					var aaa =1;
				}
					if($('#gsn_web_signature').length>0) {			
				try {
	
					
						 $.get("/my/signature/get_html",function (data) {
							zeroclipdata['gv_copy_esignature'] = data;      //.replace( /\&amp;/g, '&' )
							//alert(data.substr(0,11)+' == nosignature');
							if(data.substr(0,11) == 'nosignature') {
								 $('#modify_button').click();
								 $("#copy_disabled, #cancel_esig").remove();
								 $("#copy_disabled_setup").show();
								 debug.log("No Signature Found");
							}
							debug.log("zeroclip: setting text");
							zeroclips['gv_copy_esignature'].setText(zeroclipdata['gv_copy_esignature']);
						 });
					zeroclips['gv_copy_esignature'].addEventListener('complete', function (client, text) {	
						debug.log("zeroclip: success");
						$('#gv_copy_esignature').trigger('postCopy');
					});
					zeroclips['gv_copy_esignature'].addEventListener('mouseOver', function (client, text) {	
						 debug.log("zeroclip: resetting text");
						 zeroclips[myid].setText(zeroclipdata['gv_copy_esignature']); 
					 });
				} catch(e){
					var aaa =1;
				}
					}
				try {
				zeroclips['gv_spot_share_embed'].addEventListener('complete', function (client, text) {	
					$('#gv_spot_share_embed').trigger('postCopy');
				});
				} catch(e){
					var aaa =1;
				}
				
				try {
				zeroclips['gv_spot_share_email'].addEventListener('complete', function (client, text) {	
					$('#gv_spot_share_email').trigger('postCopy');
				});
				} catch(e){
					var aaa =1;
				}
				
		     }
		   }
						
      var mytemptimeout;
     
      function hexToR(h) {return parseInt((cutHex(h)).substring(0,2),16)}
      function hexToG(h) {return parseInt((cutHex(h)).substring(2,4),16)}
      function hexToB(h) {return parseInt((cutHex(h)).substring(4,6),16)}
      function cutHex(h) {return (h.charAt(0)=="#") ? h.substring(1,7):h}
	function tryInitSignature() {
		//initSignature has all of the signature settings loaded into javascript via the package.
		try {
			initSignature();
		} catch(e) {
		var aaa = 1;	
		}
	}
      function loadSignature() {
           $("#modify_button").click(function () { $('#update_signature').show(); $('#modify_button,#signature_stats,div.success').hide(); });
          
           $("#sample_signature a").click(function (e) {             
              $("#modify_button").click();
              var myid = $(this).attr("id");
              myid = myid.substr(0,myid.indexOf("_tgt"));
              $("#"+myid).focus();
              $("#link_editing input").css("background-color","");
              $("#"+myid).css("background-color","#FBEC5D");
              setTimeout(function () {  $("#"+myid).css("background-color",""); },3500);
              e.preventDefault(true);
              return false;
           });
           $("#fonts").ajaxAddOption("/my/signature/fonts", null,null);
           $("#backgrounds").ajaxAddOption("/my/signature/backgrounds",null,null);
           $("#buttons").ajaxAddOption("/my/signature/buttons", null, null, function () {
               setTimeout(tryInitSignature,500);
               setTimeout(refreshSignature,1000);
           });
           
           
           $("#link_editing input").change(function () {
               refreshSignature();
           });
           $("#fonts, #buttons, #backgrounds, #colors,#fontsize,#colorsb, #fontsizeb").click(function () {
                      refreshSignature();
           });
      }
	  function refreshSignature (e) {
               if($('#modify_button:visible').length==0) {
               $('#gv_copy_esig_container').hide();
               $('#copy_disabled,#cancel_esig').show();
               }
              if($("#primary_link").val().indexOf("http")<0)
                    $("#primary_link").val("http://"+$("#primary_link").val());
              
              if($("#first_link").val().indexOf("http")<0)
                    $("#first_link").val("http://"+$("#first_link").val());
                    
              if($("#second_link").val().indexOf("http")<0)
                    $("#second_link").val("http://"+$("#second_link").val());                    

              if($("#third_link").val().indexOf("http")<0)
                    $("#third_link").val("http://"+$("#third_link").val());                                        
              
              
					if($("#backgrounds").val().indexOf("_small")>-1)
						button_width = 135;
					else
						button_width = 189;
              
              data = "http://"+window.location.hostname+"/my/signature/track_image?";
              
              
              
              data_elem = { i:$("#backgrounds").val()
               ,button:$("#buttons").val()
              ,x:-12
              ,y:0
              ,center:1
              ,fs:$("#fontsizeb").val()
              ,ff:$("#fonts").val()
              ,fr:hexToR($("#colorsb").val())
              ,fg:hexToG($("#colorsb").val())
              ,fb:hexToB($("#colorsb").val())
              ,text:$("#first_linkt").val()
              ,cc:gn_customer_id
              };
              
              $.each(data_elem, function(index, value) { 
                data += "&"+index +"=" + value; 
              });
              

              $("#first_link_img").width(button_width).attr("src",data.replace("?&","?"));
              
               data = "http://"+window.location.hostname+"/my/signature/track_image?";
              
              
              
              data_elem = { i:$("#backgrounds").val()
              ,button:$("#buttons").val()
              ,x:-12
              ,y:0
              ,center:1
              ,fs:$("#fontsizeb").val()
              ,ff:$("#fonts").val()
              ,fr:hexToR($("#colorsb").val())
              ,fg:hexToG($("#colorsb").val())
              ,fb:hexToB($("#colorsb").val())
              ,text:$("#second_linkt").val()
              ,cc:gn_customer_id
              };
              
              $.each(data_elem, function(index, value) { 
                data += "&"+index +"=" + value; 
              });
              
               $("#second_link_img").width(button_width).attr("src",data.replace("?&","?"));
               
               
              data = "http://"+window.location.hostname+"/my/signature/track_image?";
              
              data_elem = { i:$("#backgrounds").val()
               ,button:$("#buttons").val()
              ,x:-12
              ,y:0
              ,center:1                             
              ,fs:$("#fontsizeb").val()
              ,ff:$("#fonts").val()
              ,fr:hexToR($("#colorsb").val())
              ,fg:hexToG($("#colorsb").val())
              ,fb:hexToB($("#colorsb").val())
              ,text:$("#third_linkt").val()
              ,cc:gn_customer_id
              };
              
              $.each(data_elem, function(index, value) { 
                data += "&"+index +"=" + value; 
              });
              
              $("#third_link_img").width(button_width).attr("src",data.replace("?&","?"));
              
              
               data = "http://"+window.location.hostname+"/my/signature/track_image?";
              
              data_elem = 
              { i:$("#backgrounds").val()
              ,x:1
              ,y:40
              ,fs:$("#fontsize").val()
              ,ff:$("#fonts").val()
              ,fr:hexToR($("#colors").val())
              ,fg:hexToG($("#colors").val())
              ,fb:hexToB($("#colors").val())
              ,cc:gn_customer_id
              };
              
               $.each(data_elem, function(index, value) { 
                data += "&"+index +"=" + value; 
              });
              
              $("#samplesignature").attr("src",data.replace("?&","?"));
              
              }						
			  
			 
