/*
    This method is the craziest method we have so far. It's responsibility is to
    make sure the fields are correctly ordered on the page. Every field has column and a row data.
    Based on the column and row we want to order the fields into lists based on columns, and then
    position in that list based on the row num. Here we go...
    Limitation: This function supports only 2 columns and !!
*/

function sortFunction(a, b) {
    var result = 0;

    var idA = a.id;
    var idB = b.id;

    var tabIndexA = Number(idA.substring(idA.lastIndexOf("_") + 1));
    var tabIndexB = Number(idB.substring(idB.lastIndexOf("_") + 1));

    if (tabIndexA > tabIndexB) {
        result = 1;
    } else if (tabIndexA < tabIndexB) {
        result = -1;
    }

    return result;
}

function createList(parent, listName, group, useBreaks) {
    if (typeof(useBreaks) == "undefined") {
    	useBreaks = true;
    }

	var list = document.createElement('div');
    $(list).addClass(listName);
    $(list).attr("id", listName);

    // append fields
    if (group.length > 0) {
        group.sort(sortFunction);
        for (var i = 0; i < group.length; i++) {
            $(list).append(group[i]);
            if (useBreaks && i > 1 && ((i + 1) % 2) === 0) {
            	var br = document.createElement("br");
            	$(br).css("clear", "both");
            	$(list).append(br);
            }
        }
    }
    // and add the list to the parent element
    $(parent).append(list);
}

function organizeFields(offerId) {
    var parent = $('#large_center_div_' + offerId);
    var group1 = $('.' + offerId + '_group_1').get();
    var group2 = $('.' + offerId + '_group_2').get();
    var group3 = $('.' + offerId + '_group_3').get();

    //Hidden group:
    var group99 = $('.' + offerId + '_group_99').get();

    // create list
    createList(parent, "group1_" + offerId, group1, false);
    createList(parent, "group2_" + offerId, group2);
    createList(parent, "group3_" + offerId, group3, false);
    createList(parent, "group99_" + offerId, group99);

}

// map for all retrieved large cutom offers
var offerMap = new Object();

// variable for testing whether they've accepted / rejected all the offers on the page
var selectedOffers = new Object();

function showLargeOfferWindow(offerId,  curPathId, curLeadId, curViewedPages, preview, test, dateFormat) {
	var pageType = "";
    showLargeOfferWindowPt(offerId, curPathId, curLeadId, curViewedPages, preview, test, dateFormat, pageType);
}

/*function doScriptExecution(offerId, curPathId, curLeadId, curViewedPages, preview, test, dateFormat) {
    var pageType = "";
                doScriptExecution(offerId, curPathId, curLeadId, curViewedPages, preview, test, dateFormat, pageType);
}*/

function doScriptExecution(offerId, curPathId, curLeadId, curViewedPages, preview, test, dateFormat, pageType) {
   // move fields around
    organizeFields(offerId);

    // get the form to post via ajax
    var options = {
        beforeSubmit: onBeforeSubmit,
        success: function(result) {
            var offerId = result.offerid;
            // enable yes and no buttons
            $(".checkable").removeAttr("disabled");
            $(".checkable").removeAttr("disabled");
            if(pageType != "COREG_QUESTIONNAIRE") {
                $('.error').empty();
            }
            if (result.status == 1) {
                $("#submit_button_" + offerId).removeAttr("disabled");
                $("#nothanks_" + offerId).removeAttr("disabled");

                //Using these two lines instead of  v.showErrors(result.data) which was not working
                $('#status_' + offerId).empty();
                $('#status_' + offerId).text(result.data);
                //NEW CONDITION IF USER GETS A VALIDATION RULE ERROR, THIS WILL DUPLICATE THE "PROCEED ON VALIDATION FAILURE" OPERATION
                if(pageType == "COREG_QUESTIONNAIRE"){
                    if($(".newSurvey").length === 0) {
                        $('#templateOfferWindow_' + offerId + ' .error').empty();
                        $('#templateOfferWindow_' + offerId).hide();
                        $('.small_container_checked_' + offerId).show();
                        $('#t1_' + offerId).find(".ynSelect input:radio").hide();
                        $('#t1_' + offerId).find(".ynSelect").css({
                            'background-image' : 'url("/media/images/fakeRadio_unselected.png")',
                            'background-repeat' : 'no-repeat',
                            'background-position' : '2px 11px'
                        });
                        $('#t1_' + offerId).find(".ynSelect:first").css({
                            'background-image' : 'url("/media/images/fakeRadio_selected.png")',
                            'background-repeat' : 'no-repeat',
                            'background-position' : '7px 11px',
                            'padding-left' : '10px'
                        });
                        $('#form_' + offerId).find('.loaderImg').hide();
                            //LEAVING THIS IN, INCASE BUSINESS WANTS TO DISABLE FIELDS
                            //$("#large_center_div_"+offerId+" :input").attr("disabled", true);
                    }
                }else {
                    showOfferRuleMismatchErrors(result, offerId);
                }

                v.focusInvalid();
                window.scroll(0, 0);
            } else {
                // write thank you note and close modal
                $('#status_' + offerId).empty();
                $('#status_' + offerId).text(result.data);

                if(pageType == "COREG_QUESTIONNAIRE"){
                    if($(".newSurvey").length === 0) {
                        $('.small_container_checked_' + offerId).show();
                        $('#t1_' + offerId).find(".ynSelect input:radio").hide();
                        $('#t1_' + offerId).find(".ynSelect").css({
                            'background-image' : 'url("/media/images/fakeRadio_unselected.png")',
                            'background-repeat' : 'no-repeat',
                            'background-position' : '2px 11px'
                        });
                        $('#t1_' + offerId).find(".ynSelect:first").css({
                            'background-image' : 'url("/media/images/fakeRadio_selected.png")',
                            'background-repeat' : 'no-repeat',
                            'background-position' : '7px 11px',
                            'padding-left' : '10px'
                        });
                        $('#form_' + offerId).find('.loaderImg').hide();
                            //LEAVING THIS IN, INCASE BUSINESS WANTS TO DISABLE FIELDS
                            //$("#large_center_div_"+offerId+" :input").attr("disabled", true);
                    }
                }
                if($(".newSurvey").length === 0) {
                    $('#templateOfferWindow_' + offerId).hide();
                }


                // add test log if required
                if (test && test != 'false') {
                    // populate test data
                    // The JQuery was not working (CR-299) for a TextArea in Firefox so using document.getElementById for the textarea elements
                    document.getElementById("payload").value = result.payload;
                    document.getElementById("responsecode").value = result.responsecode;
                    document.getElementById("url").value = result.url;
                    document.getElementById("responsedetails").value = result.responsedetails;

                    $("#debuglog").text(result.debuglog);
                }

                closeLargeOfferWindow(offerId, curPathId, curLeadId, curViewedPages, preview, test, true, pageType);

                // remember that they answered
                selectedOffers[offerId] = "true";

                if (pageType == "SINGLE_COREG")
                {

                    if (result.data.indexOf("Thank you!") >= 0)
                    {
                        document.nextform.action = "/path.html";
                        document.nextform.method = "post";
                        document.nextform.submit();
                    }
                }
            }
        },
        dataType: 'json',
        async: false
    };

    if(pageType === "COREG_QUESTIONNAIRE"){
        // ajax validation and form submit
        var v = $('#form_' + offerId).validate({
            errorPlacement: function(error, element) {
                var id = "#field_label_" + element[0].id;
                var label = $(id);
                $(label).after(error);
            },
            submitHandler: function(form) {
                $(form).ajaxSubmit(options);
                if($('.newSurvey').length < 1) {
                    $('#form_' + offerId).find('.loaderImg').fadeIn();
                    $('#form_' + offerId).find('.requiredMessage').hide();
                } else {
                    $.fancybox.showActivity();
                }
            },
            onclick: false,
            focusInvalid: false,
            focusCleanup: true
        });
    } else {
        // ajax validation and form submit
        var v = $('#form_' + offerId).validate({
            errorPlacement: function(error, element) {
                var id = "#field_label_" + element[0].id;
                var label = $(id);
                $(label).after(error);
            },
            submitHandler: function(form) {
                $(form).ajaxSubmit(options);
            }
        });
    }

    // get datefields a datepicker icon
    if (dateFormat) {
        Date.format = dateFormat.toLowerCase();
    }
    $('.date-pick_' + offerId).datepicker({
        changeYear: true,
        dateFormat: 'dd/mm/yy',
        yearRange: '1920:2040'
    });
    $("#nothanks_" + offerId).bind("click", {
        offerId: offerId,
        pageType: pageType
    },
    customNoThanks);
}

function showLargeOfferWindowPt(offerId, curPathId, curLeadId, curViewedPages, preview, test, dateFormat, pageType) {
    var data = "offerId=" + offerId + "&preview=" + preview + "&test=" + test + "&pageType=" + pageType + "&curPathId=" + curPathId + "&curLeadId=" + curLeadId + "&curViewedPages=" + curViewedPages;  
    if (!offerMap[offerId]) {
        $.ajax({
            url: "/template.html",
            type: "GET",
            dataType: "html",
            data: data,
            success: function(data) {
                offerMap[offerId] = data;
                //$('#templateOfferWindow_' + offerId).html(data);
                $(data).appendTo('#templateOfferWindow_' + offerId);

                doScriptExecution(offerId, curPathId, curLeadId, curViewedPages, preview, test, dateFormat, pageType);

                if($('.newSurvey').length > 0) {
                    $('#templateOfferWindow_' + offerId).show();
                } else {
                    $('#templateOfferWindow_' + offerId).slideDown('slow');
                }
            }
        });
    } else {
        // grab data from cache
        if($('.newSurvey').length > 0) {
            $('#templateOfferWindow_' + offerId).show();
        } else {
            $('#templateOfferWindow_' + offerId).slideDown('slow');
        }
    }
}


function showOfferRuleMismatchErrors(result, offerId) {
    var resultsField = result.fieldErrors;
    for (var name in resultsField) {
        var value = resultsField[name];
        var fieldElement = document.getElementById("field_label_" + name + "_" + offerId);
        fieldElement.innerHTML += " <span id='offerRuleErrors'  class='error' style='font-weight:normal; ' >" + value + "</span>";
    }
}


/**
 * Disables all form buttons for the duration of the request
 * @param formData
 * @param jqForms
 * @param data
 */
function onBeforeSubmit(formData, jqForms, options) {
   var offerId = jqForms[0].offerId.value;
   // disable yes and no buttons
    $(".checkable").attr("disabled", "disabled");
    $(".checkable").attr("disabled", "disabled");
    // disable submit button
    $("#submit_button_" + offerId).attr("disabled", "disabled");
    $("#nothanks_" + offerId).attr("disabled", "disabled");
    selectedOffers[offerId] = "submitted";
}

var page_type = "";
function rejectOffer(offerId, curPathId, curLeadId, curViewedPages, preview, test, pageType) {
	page_type = pageType;
    var data = "offerId=" + offerId + "&preview=" + preview + "&test=" + test + "&curPathId=" + curPathId + "&curLeadId=" + curLeadId + "&curViewedPages=" + curViewedPages;
   // disable yes and no buttons
    $(".checkable").attr("disabled", "disabled");
    $(".checkable").attr("disabled", "disabled");

    $.ajax({
        url: "/validatesubmitoffer/validatesubmitoffer.html?action=rejectOffer",
        type: "GET",
        dataType: "json",
        data: data,
        success: function(result) {
    		var offerId = result.offerid;
            $('#status_' + offerId).empty();
            $('#status_' + offerId).text(result.data);

            $(".checkable").removeAttr("disabled");
            $(".checkable").removeAttr("disabled");

            if (page_type == "SINGLE_COREG")
			{
                if ($.inArray('submit', $('#nextform').data('events')))
				{
					document.nextform.action = "/path.html";
                    document.nextform.method = "post";
					document.nextform.submit();
				}
			} else {
                $("#submit_button_" + offerId).removeAttr("disabled");
                $("#nothanks_" + offerId).removeAttr("disabled");
			}
        }
    });
    $('#templateOfferWindow_' + offerId).hide();
    
    // remember that they answered
    // this may need to be commeted
    selectedOffers[offerId] = "false";

}

function closeLargeOfferWindow(offerId, curPathId, curLeadId, curViewedPages, preview, test, isSuccess, pageType) {
    if (typeof(pageType) == 'undefined') {
        pageType = 'SINGLE_COREG';
    }
    if (!isSuccess) {
        // check the no button
        $('#yes_' + offerId).removeAttr('checked', 'checked');
        $('#no_' + offerId).attr('checked', 'checked');
        rejectOffer(offerId, curPathId, curLeadId, curViewedPages, preview, test);
        selectedOffers[offerId] = "nothanks";
    } else {
    	if(pageType == "COREG_QUESTIONNAIRE"){
    		$('.small_container_checked_' + offerId).show();
            $('#form_' + offerId).find('.loaderImg').hide();
    		$("#large_center_div_"+offerId+" :input").attr("disabled", true);
            $('.formChecked').eq(questionnaireFormNum).trigger('formSubmitted');
            questionnaireFormNum++;
    	}
    	else{
    		$('#templateOfferWindow_' + offerId).hide();
    	}
    }
}

function customNoThanks(event) {
    var offerId = event.data.offerId;
    var pageType = event.data.pageType;
    var curPathId = event.data.curPathId;
    var curLeadId = event.data.curLeadId;
    var curViewedPages = event.data.curViewedPages;
    var data = "offerId=" + offerId + "&curPathId=" + curPathId + "&curLeadId=" + curLeadId + "&curViewedPages=" + curViewedPages + "&preview=false" + "&test=false";
    var popUnder = event.data.popUnder;
    
    if(popUnder && $('#addEmail').length){
        var winfeatures = "scrollbars=1, resizable=1, toolbar=0, location=1, menubar=1, status=1, directories=0",
        link = $('#addEmail').val();
        var win2 = null;
        win2 = window.open(link, "", winfeatures);
      ///THIS HAS BEEN CHANGED DUE TO NEWER BROWSERS KILLING THE .open() FUNCTION IF USER HAS POPBLOCKER CHECKED. IF SO, THEN WE WON'T SHOW A POPUP. AS OF 1/12/12 NOTHING IS CALLING customNoThanks FUNCTION.
        if (win2 != null) {
            //win2 = window.open(whereto, "", winfeatures);
            win2.blur();
            window.focus();
        }
        //win2.blur();
        //window.focus();
    }
    
    $.ajax({
        url: "/validatesubmitoffer/validatesubmitoffer.html?action=rejectOffer",
        type: "GET",
        dataType: "json",
        data: data,
        success: function(result) {
            // write thank you note and close modal
            $('#status_' + offerId).empty();
            $('#status_' + offerId).text(result.data);
            if (pageType == "SINGLE_CUSTOM_CREATIVE" || pageType == "SINGLE_COREG")
            {
                if ($.inArray('submit', $('#nextform').data('events')))
                {
                    document.nextform.action = "/path.html";
                    document.nextform.method = "post";
                    document.nextform.submit();

                }
            }
        }
    });
    $('#templateOfferWindow_' + offerId).hide();

    // remember that they answered
    selectedOffers[offerId] = "true";
}

function isAllAcceptedRejected(atLeastOneCheck, atLeastOneViewedMessage, atLeastOneRespondMessage) {
	
    var counter = 0;
    var accepted = 0;
    var rejected = 0;
    var nothanks = 0;
    var submitted = 0;

    if (selectedOffers) {
        var o;
        for (o in selectedOffers) {
        	var answer = selectedOffers[o];
            if (answer == 'false') {
        		rejected++;
            } else if (answer == 'true') {
        		accepted++;
            } else if (answer == 'nothanks') {
        		rejected++;
        		nothanks++;
        	} else if (answer == 'submitted') {
        		submitted++;
        	}
            counter++;
        }
        // Check to see if opening at least one offer is required
        if (atLeastOneCheck != false) {
        	//Check to see if they opened one offer
        	if (counter > 1) {
        		if (accepted === 0 && nothanks === 0 && submitted === 0) {
        			alert(atLeastOneViewedMessage);
        			return false;
        		}
        	}
        }
        
        if (counter == offerCount) {
        	return true;
        }
        
    }

    alert(atLeastOneRespondMessage);
    return false;
}

/* This is called when there is No Custom offer */
/*COMMENTING THIS OUT TO SEE IF WE DONT NEED IT*/
/*function submitOffer(offerId, preview, test) {
    var pageType = "";
    var customkey = "";
    var customValue = "";
    submitOffer(offerId, preview, test, pageType, customKey, CustomValue);
}*/

function clickCPAOffer(offerId, isIframeCPA, curPathId, curLeadId, curViewedPages, preview, test) {
	selectedOffers[offerId] = "true";
    if (!isIframeCPA || isIframeCPA == 'false') {
        window.open("/cpa.html?offerId=" + offerId + "&curPathId=" + curPathId + "&curLeadId=" + curLeadId + "&curViewedPages=" + curViewedPages);
	}
    else {
		//Do nothing. For now the CPA page has only CPA or CPA IFrame offers. The CPA IFrame pages get called on Clicking Next
		// The Non IFrame CPA Offers pop up in the new window.
	}
}


/* This is called when there is No Custom offer */
function submitOffer(offerId, preview, test, pageType, customKey, customValue) {
	var data = "offerId=" + offerId + "&preview=" + preview + "&test=" + test;
	if(customKey && customValue){
		data = data+"&"+customKey+"="+customValue;
	}
    //alert("Begin submit NO custom->" + pageType);
    // disable yes and no buttons
    $(".checkable").attr("disabled", "disabled");
    $(".checkable").attr("disabled", "disabled");

    $("#submit_button_" + offerId).attr("disabled", "disabled");
    $("#nothanks_" + offerId).attr("disabled", "disabled");

    $.ajax({
        url: "/validatesubmitoffer/validatesubmitoffer.html?action=acceptOffer",
        type: "GET",
        dataType: "json",
        data: data,
        success: function(result) {

    		var offerId = result.offerid;
        	 $('.error').empty();

        	 if (result.status == 1) {

                $("#submit_button_" + offerId).removeAttr("disabled");
                $("#nothanks_" + offerId).removeAttr("disabled");


            	//Using these two lines instead of  v.showErrors(result.data) which was not working
               	$('#status_' + offerId).empty();
                $('#status_' + offerId).text(result.data);
                showOfferRuleMismatchErrors(result, offerId);
                validator.focusInvalid();
            }
            // write thank you note and close modal
            else {
				 $('#status_' + offerId).empty();
           		 $('#status_' + offerId).text(result.data);
   			 	 $('#templateOfferWindow_' + offerId).hide();
            }

        	 
            // add test log if required
            if (test && test != 'false') {
                // populate test data
                $("#payload").text(result.payload);
                $("#responsecode").text(result.responsecode);
                $("#url").text(result.url);
                $("#responsedetails").text(result.responsedetails);
            }

            // enable yes and no buttons
            $(".checkable").removeAttr("disabled");
            $(".checkable").removeAttr("disabled");
        }
    });
    selectedOffers[offerId] = "true";


    if (pageType == "SINGLE_COREG")
    {
        if ($.inArray('submit', $('#nextform').data('events')))
      	{
            setTimeout(function() {
				document.nextform.action = "/path.html";
                document.nextform.method = "post";
                document.nextform.submit();
            },
            3000);
      	}
    }
}

function clearLoadingIcon() {
    $('#loadingIconDiv').empty();
}

function offerTestResults(result, status) {
    clearLoadingIcon();
    if (result.status == 1) {
        $('#status_${offer.id}').empty();
        $('#status_${offer.id}').text(result.data);
    } else {
        // write thank you note and close modal
        $('#status_${offer.id}').empty();
        $('#status_${offer.id}').text(result.data);

        // populate test data
        $("#payload").text(result.payload);
        $("#responsecode").text(result.responsecode);
        $("#url").text(result.url);
        $("#responsedetails").text(result.responsedetails);
        $("#debuglog").html(result.debuglog);

    }
}

function addLoadingIcon(formData, jqForm, options) {
    $('#loadingIconDiv').empty();

    var loadingImg = document.createElement('img');
    $(loadingImg).attr('src', '/images/loading_red.gif');
    $(loadingImg).attr('alt', 'loading');

    $(loadingImg).appendTo("#loadingIconDiv");
}


function customSubmitButton(formData, jqForms, options) {
    var offerId = jqForms[0].offerId.value;
    $("#submitloadingspinner").show();
    document.getElementById('submit_button_' + offerId).disabled = true;
    document.getElementById('nothanks_' + offerId).disabled = true;
}

/**
 * This function is called by large single page custom creative offers
 * @param offerId
 */
function bindLargeCustomOffer(offerId, pageType, curPathId, curLeadId, curViewedPages, test) {
    if (typeof(test) == "undefined") {
		test = false;
    } else if (test == 'true') {
		test = true;
	} else {
		test = false;
	}
    var theForm = $('#form_' + offerId).get();
    //alert ("start of bindlargecustomoffer");
    // organizae fields
    organizeFields(offerId);

    // show offer.
    $('#templateOfferWindow_' + offerId).show();
    document.getElementById('templateOfferWindow_' + offerId).style.display = "block";

    // get the form to post via ajax
    var options = {
    	beforeSubmit: customSubmitButton,
        success: function(result) {
    		$("#submitloadingspinner").hide();
    		var offerId = result.offerid;
            $('.error').empty();

            if (result.status == 1) {

                $("#submit_button_" + offerId).removeAttr("disabled");
                $("#nothanks_" + offerId).removeAttr("disabled");

            	//Using these two lines instead of  v.showErrors(result.data) which was not working
               	$('#status_' + offerId).empty();
                $('#status_' + offerId).text(result.data);
                showOfferRuleMismatchErrors(result, offerId);
                v.focusInvalid();
            } else {

                $("#submit_button_" + offerId).removeAttr("disabled");
                $("#nothanks_" + offerId).removeAttr("disabled");

                // write thank you note and close modal
                $('#status_' + offerId).empty();
                $('#status_' + offerId).text(result.data);

                // remember that they answered
                selectedOffers[offerId] = "true";

                //alert ("start if bindlargecustomoffer");
                if (pageType == "SINGLE_CUSTOM_CREATIVE" || pageType == "SINGLE_COREG")
    	        {
                    if ($.inArray('submit', $('#nextform').data('events')))
            		{
						document.nextform.action = "/path.html";
                        document.nextform.method = "post";
						document.nextform.submit();
    	        	}
	            }
            }

            if (test && test != 'false') {
                // populate test data
                // The JQuery was not working (CR-299) for a TextArea in Firefox so using document.getElementById for the textarea elements
	        		document.getElementById("payload").value = result.payload;
                document.getElementById("responsecode").value = result.responsecode;
                document.getElementById("url").value = result.url;
                document.getElementById("responsedetails").value = result.responsedetails;

                $("#debuglog").text(result.debuglog);
            }
            
        },
        dataType: 'json',
        error: function() {
        	$("#submitloadingspinner").hide();
        }
    };
    
    // finally bind the no thanks button
    $('#nothanks_' + offerId + ",#addEmail").bind("click", {
        offerId: offerId,
        pageType: pageType,
        curPathId: curPathId,
        curLeadId: curLeadId,
        curViewedPages: curViewedPages,
        popUnder: ($(this).attr('id') == 'addEmail') ? true : false
    }, customNoThanks);
    
    // ajax validation and form submit
    var v = $('#form_' + offerId).validate({
        errorPlacement: function(error, element) {
            var id = "#field_label_" + element[0].id;
            var label = $(id);
            $(label).after(error);
        },
        submitHandler: function(form) {
            if($('.blocCoregPI').size() > 0){
                if($('input[id*="repOui"]').is(':checked')){
                    $(form).ajaxSubmit(options);
                }else{
                    $('#nothanks_' + offerId).trigger('click');
                }
            }else{
                if($('#popLinkValue').length){
                    window.open($('#popLinkValue').val(), 'offerWindow');
                }
                $(form).ajaxSubmit(options);
            }
        }
    });
    
    // instantiate date picker. notice it is set for European date format,
    // have to pass dateFormat into function if want to expand on it
    $('.date-pick_' + offerId).datepicker({
        changeYear: true,
        dateFormat: 'dd/mm/yy',
        yearRange: '1920:2040'
    });

    //, curPathId: curPathId, curLeadId: curLeadId
    //    $("#submit_button_"+offerId).bind("click", {offerId: offerId, pageType: pageType}, customSubmitButton);
}

function beforeNoThanks(formData, jqForms, options) {

	var offerId = jqForms[0].offerId.value;

    document.getElementById('submit_button_' + offerId).disabled = true;
    document.getElementById('nothanks_' + offerId).disabled = true;
}



/* POP UNDER STUFF */
var once_per_session = 0;
var winfeatures = "scrollbars=1, resizable=1, toolbar=0, location=1, menubar=1, status=1, directories=0";
var popunder = "";
var pathid = "";
function get_cookie(Name) {
	var search = Name + "=";
	var returnvalue = "";
	if (document.cookie.length > 0) {
		offset = document.cookie.indexOf(search);
		if (offset != -1) {
			offset += search.length;
			end = document.cookie.indexOf(";", offset);
            if (end == -1) {
				end = document.cookie.length;
            }
			returnvalue = unescape(document.cookie.substring(offset, end));
		}
	}
	return returnvalue;
}

function loadpopunder() {
    if (popunder == "" || pathid == ""){
		return false;
    }
	var whereto = "";
	if (!popunder.match(/http|html/)) {
		//Use as cpa pop offer
        //Get the leadid
		var leadid = '';
        if (typeof(royalmail_leadid) != "undefined" && royalmail_leadid != "") {
			leadid = royalmail_leadid;
        } else if (typeof(aussiemail_leadid) != "undefined" && aussiemail_leadid != "") {
			leadid = aussiemail_leadid;
		} else if (typeof(mail_leadid) != "undefined" && mail_leadid != "") {
			leadid = mail_leadid;
		}else if (typeof(olp_sLeadId) != "undefined" && olp_sLeadId != "") {
			leadid = olp_sLeadId;
		}

        if (leadid != "" && pathid != "") {
			popunder = "/cpa.html?offerId=" + popunder + "&curPathId=" + pathid + "&curLeadId=" + leadid + "&curViewedPages=0&ispopunder=true";
		}

		whereto = popunder;
	} else {
		whereto = popunder + "&first=" + document.getElementById("firstName").value + "&last=" + document.getElementById("lastName").value + "&email=" + document.getElementById("email").value;
	}

	var win2 = null;
    win2 = window.open(whereto, "", winfeatures);
    ///THIS HAS BEEN CHANGED DUE TO NEWER BROWSERS KILLING THE .open() FUNCTION IF USER HAS POPBLOCKER CHECKED. IF SO, THEN WE WON'T SHOW A POPUP
    if (win2 != null) {
        //win2 = window.open(whereto, "", winfeatures);
        win2.blur();
    	window.focus();
    }

	//win2.blur();
	//window.focus();
}

function loadornot() {
    if (get_cookie('popunder') == '') {
        loadpopunder();
        document.cookie = "popunder=yes";
    }
}

function pop() {
    if (once_per_session === 0){
		loadpopunder();
    }else{
		loadornot();
    }
}

function appendScriptElement(el, src){
    var sTag = document.createElement('script');
    sTag.type = 'text/javascript';
    sTag.src = src;
    $('#optInHere').replaceWith(sTag);
    
}

$().ready(function() {

    $('.smallConfirm:not(.simpleOptin) input:not(.customMini)').dblclick(function() {
        return false;
    });

    $('.smallConfirm:not(.simpleOptin) input:not(.customMini)').click(function() {
        var vField = $(this).siblings('input'),
            vType = vField.attr('class'),
            vVal = vField.val().replace(/[ ']/g, "").split(',');
        if (vType == 'reject') {
            rejectOffer(vVal[0], vVal[1], vVal[2], vVal[3], vVal[4], vVal[5], vVal[6]);
        } else {
            clickCPAOffer(vVal[0], vVal[1], vVal[2], vVal[3], vVal[4], vVal[5], vVal[6]);
        }
    });
    
    /*$('radio[value="1"]').click(function(e){
        $(this).parents('form').submit();
    });*/

    questionnaireFormNum = 0;

    function stepForms() {

        var questionnaireForms = $('.template1.questionnaire');

        function fakeRadioReplace(iter, img1, img2) {
            questionnaireForms.eq(iter).find(".ynSelect").css({
                'background' : 'url(' + img1 + ') no-repeat 2px 11px',
                'background-image' : 'url(' + img1 + ')',
                'background-repeat' : 'no-repeat',
                'background-position' : '2px 11px'
            });
            questionnaireForms.eq(iter).find(".ynSelect:first").css({
                'background-image' : 'url(' + img2 + ')',
                'background-repeat' : 'no-repeat',
                'background-position' : '7px 11px',
                'padding-left' : '10px'
            });
        }

        $.each(questionnaireForms, function(i) {

            if(i !== 0) {
                questionnaireForms.eq(i)
                      .fadeTo('slow', 0.4)
                      .bind('mouseup', function() {
                          alert('Please select "Yes" or "No" to each offer before proceeding to the next offer.');
                      });
                questionnaireForms.eq(i).find("input:radio").hide();
                fakeRadioReplace(i, "/media/images/fakeRadio.png", "/media/images/fakeRadio.png");
            }

            function showNextForm() {
                if(questionnaireForms.eq(i).find('.formChecked').css('display') == 'none') {
                    questionnaireForms.eq(i)
                      .fadeTo('slow', 1)
                      .unbind('mouseup');
                    questionnaireForms.eq(i).find("input:radio").show();
                    questionnaireForms.eq(i).find(".ynSelect").css({
                        'background' : 'none'
                    });
                    questionnaireForms.eq(i).find(".ynSelect:first").css({
                        'padding-left' : '0px'
                    });

                    questionnaireFormNum++;
                }
            }

            $(this).find('.checkable.no').click(function() {
                showNextForm();
            });
            $(this).find('.checkable.yes').click(function() {
                showNextForm();
            });

            i++;
        });
    }
    if($('.newSurvey').length < 1) {
        stepForms();
    }

});

