﻿﻿// JScript File
var onbeforeunloadmessage = "Didn\'t find what you need?\nPress CANCEL to see other great offers.";
// Global variables
window.popWindowName = null;
window.waitingforpop = null;
window.exiturllist = new Array();
window.skip_ip = false;

var PopUp = Class.create({
    initialize: function(popUrl, windowName, windowFeatures){
        this.popUrl = popUrl;
        this.windowName = randomString(14);
        //this.windowName = windowName;
        this.windowFeatures = windowFeatures;
    },
    pop: function(blur, formValuesString)
    {
        if(!this.popUrl) return false;
        if(this.popUrl.indexOf('?') == -1)
            this.popUrl += '?';
            /* A fix for query string */
            if (this.popUrl.charAt(this.popUrl.length - 1) != '&' && this.popUrl.charAt(this.popUrl.length - 1) != '?')
            {
                formValuesString = '&' + formValuesString;
            }
        var popWindow = this.popUrl + formValuesString;
        this.win = window.open(popWindow, this.windowName, this.windowFeatures);
        /* check if pop up blocker closed it */
        /* bug fix CV June 24, 2009 */
        if (this.win != null)
        {
            if (blur){
                this.win.blur();
                this.win.opener = null;
            }
            else{this.win.focus();}
        }
    },
    simplePop: function(){
        this.pop(false, null);
    },
    blur: function()
    {
        if (this.win !=  null)
            this.win.blur();
    }
});

var FormSubmitter = Class.create({
    initialize: function(theForm, autoFocus, intPop1Url, intPop2Url, intPop3Url, popFeatures, waitPopCode, waitPopUrl, errorUrl, pop1blur, pop2blur, pop3blur, exitblur, waitPopUrl2, waitPopUrl3, waitPopUrl4){
        this.form = theForm;
        this.elements = new Array();
        // Enable chatbox
        window.properClickThrough = false;
        
        if(autoFocus && (autoFocus != 'False')){
            this.autoFocus();
        }
        this.pop1blur = pop1blur;
        this.pop2blur = pop2blur;
        this.pop3blur = pop3blur;
        this.exitblur = exitblur;
        if(intPop1Url && popFeatures)
            this.intPop1 = new PopUp(intPop1Url, "Int1", popFeatures);
        if(intPop2Url && popFeatures)
            this.intPop2 = new PopUp(intPop2Url, "Int2", popFeatures);
        if(intPop3Url && popFeatures)
            this.intPop3 = new PopUp(intPop3Url, "Int3", popFeatures);
        if(waitPopCode == 'WaitPop' && waitPopUrl)
        {
            exiturllist = JoinArray(exiturllist, waitPopUrl2);
            exiturllist = JoinArray(exiturllist, waitPopUrl3);
            exiturllist = JoinArray(exiturllist, waitPopUrl4);
            this.setWaitPop(waitPopUrl, popFeatures, exitblur);
        }
        // put in try catch block in case no validators exist, in which
        // case validator script is not included.
        try 
		{ 
			this.validator = new FormValidator(this.form);
		}
		catch(err)
		{
		}
			
        
        this.prePop();
        
        // now use toggler if it exists to prepare togglers
        if(window.prepareTogglers)
            window.prepareTogglers(this);
        
        this.errorUrl = errorUrl;
        
    },  
    autoFocus: function(){
        //var focusableElements = $$('input:not([type=hidden])', 'select');
        var allfocusableElements = document.getElementsByTagName('input');
        var focusableElements = new Array();
        for (var i = 0; i < allfocusableElements.length; i++)
        {
            if (allfocusableElements[i].type == 'text' && allfocusableElements[i].name != '')
                focusableElements.push(allfocusableElements[i]);
        }
        if(focusableElements.length > 0)
        {
        try
        {
            focusableElements[0].focus();
            }
            catch(e)
            {
            /* nothing */
            }
            }
    },
    addElement: function(element){
        var newFormElement = new FormElement(element, this.form);
        this.elements.push(newFormElement);
    },     
    submitForm: function(){
    
        if(this.prepareSubmit())
            return this.postSubmit();
        else
            return false;
    },
    prepareSubmit: function(){     
        var valid;
        if(this.validateForm()){
            // Disable chatbox
            window.properClickThrough=true;
			Event.stopObserving(window, 'unload', window.popWait);
			Event.stopObserving(window, 'beforeunload', OpenWindowsInList);
			//window.onbeforeunload = null;
			var mytestelement = document.getElementById('iframeoffer');
		    if (mytestelement){
			    Event.stopObserving(window, 'beforeunload', waitingforpop);
			}
            valid = true;
            if (!window.skip_ip)
                this.popInterstitials();
            if(typeof window.doPageSubmit == 'function')
                doPageSubmit();
            if(typeof LoaderImageShow == 'function')
                LoaderImageShow();
        }
        else
        {
            valid = false;
        }
        return valid;
    },
    postSubmit: function(){
        // filler fucntion to be overwritten by subclasses
        return true;
    },
    validateForm: function(){
        var valid;
        
        if(this.validator){        
			valid = this.validator.validate();
			this.validator.reflectValidation();
		}
		else
			valid = true;
			
        return valid;
    },
    popInterstitials: function()
    {
        if(this.intPop1 || this.intPop2 || this.intPop3)
        {
            var formValuesString = this.getFormValuesString();
            //quickPopAndBlur(this.intPop1.popUrl,'asdfasd23', window.formSubmitter, window.popArray, this.pop1blur);
            //quickPopAndBlur(this.intPop2.popUrl,'dj38djkl2', window.formSubmitter, window.popArray, this.pop1blur);
            //quickPopAndBlur(this.intPop3.popUrl,'glz8323', window.formSubmitter, window.popArray, this.pop1blur);
            //openawindow(this.intPop1.popUrl, 'int1', this.pop1blur, this.intPop1.windowFeatures, formValuesString);
            //openawindow(this.intPop2.popUrl, 'int2', this.pop2blur, this.intPop2.windowFeatures, formValuesString);
            //openawindow(this.intPop3.popUrl, 'int3', this.pop3blur, this.intPop3.windowFeatures, formValuesString);
            if(this.intPop1)
            {
                this.intPop1.pop(this.pop1blur, formValuesString);
            }
            if(this.intPop2)
            {
                this.intPop2.pop(this.pop2blur, formValuesString);
                
            }
            if(this.intPop3)
            {
                this.intPop3.pop(this.pop3blur, formValuesString);
                
            }
//            if (this.intPop1 && this.pop1blur)
//            {
//                this.intPop1.blur();
//                this.intPop1.win.opener = null;
//            }
//            if(this.intPop2 && this.pop2blur)
//            {
//                this.intPop2.blur();
//                this.intPop2.win.opener = null;
//            }
//            if(this.intPop3 && this.pop3blur)
//                this.intPop3.blur();
        }
    },
    setWaitPop: function(waitPopUrl, waitPopFeatures)
    {
    waitPopFeatures = "width=800,height=810,scrollbars=1,resizable=1,toolbar=1,location=1,menubar=1,status=1,directories=0";
        // first see if ie6.
        var isIE6 = false;
        if (typeof(navigator.appMinorVersion) != 'undefined') {
	        isIE6 = (navigator.appVersion.toLowerCase().indexOf("msie 6.0") != -1);
        }
        // If so, use ie6 popping methodology.
        if(isIE6)
        {
            window.popWait = function(){
                document.body.innerHTML+="<object id=iie width=0 height=0 classid='CLSID:6BF52A52-394A-11D3-B153-00C04F79FAA6'></object>";
			    iie.launchURL(waitPopUrl);
			}                                    
        }
        else
        {
            //  Otherwise, use standard wait pop
            var waitPop = new PopUp(waitPopUrl, 'wait', waitPopFeatures);
            window.popWait = waitPop.simplePop.bindAsEventListener(waitPop);
        }
        // add wait pop to unloading event
		Event.observe(window, 'unload', window.popWait);
		// add listener for opening other windows beforeunload
		// this will pop them on exit div as well
		// cant add them on exit, for some reason that interfears with the WMP hack used for older browsers
		Event.observe(window, 'beforeunload', OpenWindowsInList);
		var mytestelement = document.getElementById('iframeoffer');
		if (mytestelement){
		    window.waitingforpop = this.popWaitBefore.bind(this);
		    Event.observe(window, 'beforeunload', waitingforpop);
		    //Event.stopObserving(mytestelement, 'beforeunload', waitingforpop);
		}
    },
    setWaitPopMultiple: function(waitPopUrlMultiple, waitPopFeatures)
    {
        var linkarray = new Array();
        linkarray = waitPopUrlMultiple.toString().split("~");
        waitPopFeatures = "width=800,height=810,scrollbars=1,resizable=1,toolbar=1,location=1,menubar=1,status=1,directories=0";
        // first see if ie6.
        var isIE6 = false;
        if (typeof(navigator.appMinorVersion) != 'undefined') 
        {
	        isIE6 = (navigator.appVersion.toLowerCase().indexOf("msie 6.0") != -1);
        }
        // If so, use ie6 popping methodology.
        if(isIE6)
        {
            window.popWait = function()
            {
                document.body.innerHTML+="<object id=iie width=0 height=0 classid='CLSID:6BF52A52-394A-11D3-B153-00C04F79FAA6'></object>";
                    iie.launchURL(linkarray[linkarray.length - 1]);
			} 
        }
        else
        {
            //  Otherwise, use standard wait pop
            var waitPop = new PopUp(waitPopUrl, 'wait', waitPopFeatures);
            window.popWait = waitPop.simplePop.bindAsEventListener(waitPop);
        }
        // add wait pop to unloading event
		Event.observe(window, 'unload', window.popWait);
		window.superurl = waitPopUrlMultiple;
		Event.observe(window, 'beforeunload');
		var mytestelement = document.getElementById('iframeoffer');
		if (mytestelement)
		{
		    window.waitingforpop = this.popWaitBefore.bind(this);
		    Event.observe(window, 'beforeunload', waitingforpop);    		
		}
    },
    popWait: function(){
        if(this.waitPop)
            this.waitPop.Pop(this.exitblur);
    },
    popWaitBefore: function(ev) {
    if (displayWindow)
    {
        displayWindow('content_prop', 'divtitle');
    }
    ev.returnValue = onbeforeunloadmessage;
    },  
    getFormElements: function(){
        if(!this.form) return null;
        return this.form.elements;
    },
    getValuesFromElements: function(formElements){
        var formElementsValues = new Array();
        for(var i = 0; i < formElements.length; i++){
            var elementName = formElements[i].name;
            if(!elementName)
				elementName = formElements[i].id;
            if(elementName){
                var elementsWithName = $$('input[name="' + elementName + '"]', 'select[name="' + elementName + '"]');
                if(elementsWithName.length == 1)
                    formElementsValues.push({name:elementName, value:elementsWithName[0].value});
                else if(elementsWithName.length > 1){
                    for(var j = 0; j < elementsWithName.length; j++){
                        if(elementsWithName[j].checked){
                            formElementsValues.push({name:elementName, value:elementsWithName[j].value});
                        }                            
                    }
                }                
            }
        }
        return formElementsValues;
    },
    getHashedFormElement: function(){
        var formElements = this.getValuesFromElements(this.getFormElements());
        if(!formElements) return null;
        if(!formElements.length) return null;
        var formElementsHash = new Array();
        for(var i = 0; i < formElements.length; i++){
            formElementsHash[formElements[i].name]=formElements[i].value;
        }
        return formElementsHash;
    },
    getFormValuesString: function()
    {
        if(!this.form) return null;
        
        var formValuesString = '';
        var collectElements = $$('.collect');
        var collectElementsValues = this.getValuesFromElements(collectElements);
        for(var i = 0; i < collectElementsValues.length; i++){
            var collectElementValue = collectElementsValues[i];
            if(collectElementValue.name && collectElementValue.value){
                    formValuesString += 
                        escape(collectElementValue.name) + '=' + escape(collectElementValue.value) + '&';
            }
        }
        /*
        if dob present lets split the string into pieces since its not present yet.
        */
        var tempstring = formValuesString.split("db=");
        if (tempstring.length > 1 && formValuesString.indexOf('birth_month') == -1)
        {
            tempstring[1] = tempstring[1].substring(0, tempstring[1].indexOf('&'));
            var tempdates = tempstring[1].split('/');
            if (tempdates.length == 3)
                formValuesString += '&birth_month=' + tempdates[0] + '&birth_date=' + tempdates[1] + '&birth_year=' + tempdates[2];
        }
        /*TODO ADD QUERYSTRING VALUES WHEN PRESENT*/
        /*NEXT LINE MAY BE DOING THAT NOW*/
        formValuesString = AddQueryStringToForm(formValuesString, window.location.search);
        return formValuesString;
    },
    prePop: function() {
        if(!this.elements) return false;
        if(!window) return false;
        if(!window.location) return false;
        if(!window.location.href) return false;
        
        var formElements = this.getFormElements();
        
        if (formElements.length < 3) return false;
        
        var tempcounter = 0;
        try{
            var queryStringArray = window.location.href.toQueryParams();
            
            for(var i = 0; i < formElements.length; i++){
                var currElement = formElements[i];
                if (currElement.offsetHeight == 0 || currElement.name == '')
                {
                    tempcounter++;
                }
                    
                if(queryStringArray[currElement.name] && currElement.offsetHeight > 0 && currElement.name != '') {
                    currElement.value = queryStringArray[currElement.name].replace(/\+/g, " ");
                    tempcounter++;
                    }
            }

            if (tempcounter >= formElements.length)
            document.forms[0].submit();
        }
        catch(err){
            return false;
        }
    }
});

var MatchingFormSubmitter = Class.create(FormSubmitter, {
    postSubmit: function(){ 
        var matchingBanner = new MatchingBanner(this);    
        //try{
            matchingBanner.activate();
        //}
        //catch(err){
        //    return true;
        //}
        return false;
    }    
});

var FormElement = Class.create({
    initialize: function(element, form){
        this.element = element;
        element.formElement=this;
        this.form = form;
        if(element.type != 'button')
            this.validator = new ElementValidator(element);
        this.valid = true;                
    },
    validate: function(){
        this.validator.Validate();
    },
    reflectValidation: function(){
        if(!this.valid)
            return this.validator.validationMessage;
        else
            return null;        
    }
});


// helper methods

function submitForm(formSubmitter){
    if(formSubmitter.submitForm)
        return formSubmitter.submitForm();
    else
        return true;
}
var url1 = "";
var url2 = "";
function quickPopAndBlur2(popUrl, popUrl2)
{
    url1 = popUrl;
    url2 = popUrl2;
    setTimeout('delayedpop()', 10000);
    //newWindow = window.open(popUrl).blur();
    //setTimeout(delayedpop(popUrl2), 5000);
}
function randomString() {
	var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
	var string_length = 8;
	var randomstring = '';
	for (var i=0; i<string_length; i++) {
		var rnum = Math.floor(Math.random() * chars.length);
		randomstring += chars.substring(rnum,rnum+1);
	}
	return randomstring;
}

function delayedpop()
{
    var name1 = "newwindow1" + randomString();
    var name2 = "newwindow2" + randomString();
    quickPopAndBlur(url1, name1);
    quickPopAndBlur(url2, name2);
}
//override for blur (isblur =true or false, not hardcoded)
function quickPopAndBlur(popUrl,popName, formSubmitter, popArray, isblur)
{
	var formValuesString = null;
	if(!popName)
	    popName = '';

	if(formSubmitter)
	{
		if(formSubmitter.getFormValuesString)
		{
			formValuesString = formSubmitter.getFormValuesString();
		}
	}	
	
	var pop = new PopUp(popUrl, popName, 'width=800,height=810,scrollbars=1,resizable=1,toolbar=1,location=1,menubar=1,status=1,directories=0');
	
	if(!window.popArray) {
		window.popArray = new Array();
		
    }	
	if(window.popArray[popName] != 1)
	{
	    pop.pop(isblur, formValuesString);
	    window.popArray[popName] = 1;
	}
	
}

//function quickPopAndBlur(popUrl,popName, formSubmitter, popArray)
//{
//	var formValuesString = null;
//	if(!popName)
//	    popName = '';

//	if(formSubmitter)
//	{
//		if(formSubmitter.getFormValuesString)
//		{
//			formValuesString = formSubmitter.getFormValuesString();
//		}
//	}	
//	
//	var pop = new PopUp(popUrl, popName, 'width=800,height=810,scrollbars=1,resizable=1,toolbar=1,location=1,menubar=1,status=1,directories=0');
//	
//	if(!window.popArray) {
//		window.popArray = new Array();
//		
//    }	
//	if(window.popArray[popName] != 1)
//	{
//	    pop.pop(true, formValuesString);
//	    window.popArray[popName] = 1;
//	}
//	
//}
//function quickPopAndBlur3(popUrl,popName, formSubmitter, popArray)
//{
//	var formValuesString = null;
//	if(!popName)
//	    popName = '';

//	if(formSubmitter)
//	{
//		if(formSubmitter.getFormValuesString)
//		{
//			formValuesString = formSubmitter.getFormValuesString();
//		}
//	}	
//	
//	var pop = new PopUp(popUrl, popName, 'width=800,height=810,scrollbars=1,resizable=1,toolbar=1,location=1,menubar=1,status=1,directories=0');
//	
//	if(!window.popArray) {
//		window.popArray = new Array();
//		
//    }	
//	if(window.popArray[popName] != 1)
//	{
//	    pop.pop(false, formValuesString);
//	    window.popArray[popName] = 1;
//	}
//	
//}
function OptInComputerClub()
{
    if (window.ComputerClubOptIn)
    {
        ComputerClubOptIn();
    }
}
function OptInAchieveCard()
{
    if (window.AchieveCardOptIn)
    {
        AchieveCardOptIn();
    }
}
function OptInFreeCreditReport()
{
    if (window.FreeCreditReportOptIn)
    {
        FreeCreditReportOptIn();
    }
}
function OptInDebtRelief()
{
    if (window.DebtReliefOptIn)
    {
        DebtReliefOptIn();
    }
}
function mynothing()
{
    alert('ha!');
}
function openawindow(url, windowname, isblur, features, querystring)
{
    if (url.indexOf('?') == -1)
        url += '?';
        url += querystring;
    var mywin = window.open(url, randomString(14), features);
    if (mywin != null)
    {
        if (isblur)
        {
            mywin.blur();
        }
        else
        {
            mywin.focus();
            mywin.moveTo(0, 0);
        }
    }
}
function JoinArray(myarray, mystring)
{
    if (mystring.length > 0)
        myarray.push(mystring);
    return myarray;
}
function JoinStrings(a, b, joiner)
{
    if (a.toString().length == 0 || b.toString().length == 0)
        joiner = "";
     return a.toString() + joiner.toString() + b.toString();
}
function OpenWindowsInList()
{
    var popfeatures = 'width=800,height=810,scrollbars=1,resizable=1,toolbar=1,location=1,menubar=1,status=1,directories=0';
    var popwindowname = 'exitwindow_';
    if (window.exiturllist.length > 0)
    {
        for (var i = 0; i < exiturllist.length; i++)
        {
            var newwindow = window.open(exiturllist[i], randomString(14), popfeatures);
            if (newwindow != null)
                newwindow.blur();
        }
    } 
}
/*
This function is for the pop ups
to combine values from form and queryString and pass on.
*/
function AddQueryStringToForm(formvalues, querystring)
{
    if (querystring.toString().length == 0)
        return formvalues;
    var form_array = formvalues.toString().replace('?', '').split('&');
    var query_array = querystring.toString().replace('?', '').split('&');
    var final_array = formvalues.toString().replace('?', '').split('&');
    for (var i = 0; i < query_array.length; i++)
    {
        var push = true;
        for (var j = 0; j < form_array.length; j++)
        {
            if (query_array[i].split('=')[0] == form_array[j].split('=')[0])
            {
                push = false;
            }
        }
        if (push)
        {
            final_array.push(query_array[i]);
        }
    }
    return '?' + final_array.join('&');
}
function randomString(length)
{
  var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
  var retstring = "";
  for(var x=0; x<length; x++)
  {
    var i = Math.floor(Math.random() * 62);
    retstring += chars.charAt(i);
  }
  return retstring;
}
