﻿var my_surveys = "my_surveys_ajax.aspx";
// JScript File
/* NEW SCRIPT START FROM HERE */
var Surveys = [];
function between(v, start, end) {
    return v.substring(v.indexOf(FmtS) + FmtS.length, v.indexOf(FmtE));
}
//to Trim() string
String.prototype.trim = function() { return (this.replace(/^[\s\xA0]+/, "").replace(/[\s\xA0]+$/, "")) }

//to startsWith() string
String.prototype.startsWith = function(str)
{ return (this.match("^" + str) == str) }

//to endsWith() string
String.prototype.endsWith = function(str)
{ return (this.match(str + "$") == str) }

//'HR 2010-03-23
//'Already declared in questions.js

//function aType(name, divNum, layouts) {
//    this.name = _default(name, "");
//    this.divNum = _default(divNum, -1);
//    this.layouts = _default(layouts, []);
//}

//var aTypes = [
//	new aType("Text input entry", -1, ["Single line TextBox", "Comment", "Eassay Box", "Descriptive Text"]),
//	new aType("Multiple Choice - Multiple Answers", 0, ["CheckBox", "List Box"]),
//	new aType("Multiple Choice - Single Answer", 0, ["Radio", "Drop down"]),
//	new aType("Date/Time", -1, []),
//	new aType("Image", -1, []),
//	new aType("Rating Scale", 0, []),
//	new aType("Multiple TextBox with labels", 1, []),
//	new aType("Matrix Of Choices - One answer per Row", 2, []),
//	new aType("Matrix Of Choices - Multiple answers per Row", 2, []),
//	new aType("Demographic Info", 3, [])
//];

function formatString() {
    if (arguments.length == 0) return "";
    var _format = arguments[0] || "";
    var _ret = _format + "";
    var r = null;
    try {
        for (var i = 1; i < arguments.length; i++) {
            r = new RegExp("\\{" + (i - 1) + "\\}", "g");
            _ret = _ret.replace(r, arguments[i] == null ? "" : arguments[i].toString());
        }
    } catch (e) { }
    return _ret;
}

function dateToString(date_obj, format) {
    if (_default(date_obj, "") === "")
        return "";
    var specifiers = ["y", "M", "d", "h", "m", "s"];
    var ret = format + "";
    //ret = ret.replace(/y/g, date_obj.getYear() + 1900)
    ret = ret.replace(/y/g, date_obj.getFullYear())
                .replace(/M/g, date_obj.getMonth() + 1)
                .replace(/d/g, date_obj.getDate())
                .replace(/h/g, date_obj.getHours())
                .replace(/m/g, date_obj.getMinutes())
                .replace(/s/g, date_obj.getSeconds());
    return ret;
}

//Adding extention method to jQuery
(function($) {
    jQuery.fn.delayedCall = function(callback, time) {
        var o = $(this);
        setTimeout(function() { callback.apply(o); }, time);
        return o;
    };
})(jQuery);


function showProgress(msg, timeout) {
//alert('progress' + msg);
    jQuery("#ErrorContainer > div").hide();
    var maxCharLimit = 45;
    var obj = jQuery("#NotificationDiv").eq(0);
    if (obj) {
        if (msg == null || msg.length == 0) {
            obj.hide();
        } else {
            jQuery("#msg_link", obj).unbind("click").bind("click", function() {
                jQuery("#msg_details").html(msg);
                popO("#msg_details", { position: 'center', buttons: { Ok: function() { $(this).dialog('close'); } } });
                //jQuery("#msg_details").dialog({ modal: true, buttons: { Ok: function() { $(this).dialog('close'); } }, width: 600, height: "auto" }).dialog("open");
            });
            if (jQuery(msg).length == 0) {
                jQuery("#msg_contents", obj).html(msg.length > maxCharLimit ? msg.substring(0, maxCharLimit) + "..." : msg);
            } else {
                jQuery("#msg_contents", obj).html("Please click on 'Info' for more details.");
            }
            obj.show(0);
            if (timeout != undefined) {
                obj.delayedCall(function() {
                    $(this).hide();
                }, timeout);
            }
        }
    }
}

function showError(msg) {
    //jQuery(".popError").hide();
    msg = msg.replace(/&lt;/g, "<").replace(/&gt;/g, ">");
    //alert(msg);
    if (msg.indexOf("popLogin") == 0){
        jQuery(".popError").show().html(msg.replace("popLogin",""));
        jQuery("#NotificationDiv").hide();
        return;
    }
    
    jQuery("#ErrorContainer > div").hide();
    var maxCharLimit = 48;
    jQuery("#NotificationDiv").hide();
    var obj = jQuery("#ErrorDiv");
    if (obj) {
        jQuery("#error_link", obj).unbind("click").bind("click", function() {
            jQuery("#error_details").html(msg);
            popO("#error_details", { position: 'center', buttons: { Ok: function() { $(this).dialog('close'); } } });
            //jQuery("#error_details").dialog({ modal: true, buttons: { Ok: function() { $(this).dialog('close'); } }, width: 600, height: "auto" }).dialog("open");
        });
        if (jQuery(msg).length == 0) {
            jQuery("#error_content", obj).html(msg.length > maxCharLimit ? msg.substring(0, maxCharLimit) + "..." : msg);
        } else {
            jQuery("#error_content", obj).html("Oops!! Few errors. Click \"Error\" for details.");
        }
        obj.show();
    }
    //jQuery(".popError").show().html(msg);
}

function objectify(datatable) {
    var data = datatable;
    var _rows = [];
    var temp = {};
    var r = null;
    for (var i = 0; i < data.table.rows.length; i++) {
        r = data.table.rows[i];
        temp = {};
        for (var j = 0; j < data.table.cols.length; j++) {
            temp[data.table.cols[j]] = r[j];
        }
        _rows.push(temp);
    }
    data.table.rows = _rows;
    return data;
}
var DAY = 24 * 60 * 60 * 1000, MONTH = 30 * DAY;

function _default(val, defaultVal) {
    return val === undefined || val === null ? defaultVal : val;
}

function rtrim(str, pattern) {
    return str.replace(pattern + "$", "");
}

jQuery.postJSON = function(url, data, callback) {
    window.JSON = null;
    showProgress("Processing...");
    jQuery.ajax({
        url: url,
        data: data,
        cache: false,
        dataType: "text",
        type: "POST",
        error: function(xhr, ts, err) {
            if (ts == "timeout") {
                showError("Couldn't connect to server. Please try again.");
            } else {
                showError("Irrecoverable error. Please try again.");
            }
        },
        success: function(d, ts, xhr) {
            eval("var d = " + d);
            if (d.error) {
                showError(d.error.replace(/&lt;/g, "<").replace(/&gt;/g, ">"));
            } else {
                showProgress("");
                callback(d);
            }
        }
    });
};

jQuery.fn.outerHTML = function() {
    return jQuery('<div></div>').append(this.eq(0).clone()).html();
};

/* SURVEY SCRIPT FOR ASP CONTROL ON FORM ---

var Surveys = [];
function loadAllSurvey(){

loadSurveys("SurveyList");
}

function loadS(id){
id = _default(id,-1);
var s = jQuery(".box_area").eq(0);
resetForm("#add_s");
clearSurveyForm();
if (id && id != "undefined" && id != -1) {
jQuery.postJSON("ajax.aspx", { action: "get", entity: "survey", id: id }, function(d) {
if (d == undefined || d.table == undefined) return;
jQuery("[id$='_tbName']").val(d.table.rows[0][2]);
jQuery("[id$='_tbWelcomeMessage']").val(d.table.rows[0][8]);
jQuery("[id$='_tbThankYou']").val(d.table.rows[0][4]);
d.table.rows[0][4].substring(7,0)=='http://' ? jQuery("[id$='_rdForwardPageLink']")[0].checked = 1 : jQuery("[id$='_rdThankYouMessage']")[0].checked = 1;
jQuery("[id$='_cbEmailNotification']")[0].checked = d.table.rows[0][3]=='y' ? 1 : 0;
jQuery("[id$='_cbAllowMultipleAttempt']")[0].checked = d.table.rows[0][10]=='y' ? 1 : 0;
jQuery("[id$='_hdnId']").val(d.table.rows[0][0]);
});
}
popO("#add_s");
}

function clearSurveyForm(){
jQuery("[id$='_tbName']").val('');
jQuery("[id$='_tbWelcomeMessage']").val('');
jQuery("[id$='_tbThankYou']").val('');
jQuery("[id$='_rdForwardPageLink']")[0].checked = 0;
jQuery("[id$='_rdThankYouMessage']")[0].checked = 0;
jQuery("[id$='_cbAllowMultipleAttempt']")[0].checked = 0;
jQuery("[id$='_cbEmailNotification']")[0].checked = 0;
jQuery("[id$='_hdnId']").val('');
}
function SaveS() {
var id = jQuery("[id$='_hdnId']").val();
id = id != null && id != "undefined" && id != "" ? parseInt(id) : -1;
var s = {};
s.id = id;
s.name = jQuery("[id$='_tbName']").val();
//s.logo_url = jQuery("#fuLogo").val();
s.welcome_message = jQuery("[id$='_tbWelcomeMessage']").val();
s.thankyou_message = jQuery("[id$='_tbThankYou']").val();
s.email_notification = jQuery("[id$='_cbEmailNotification']")[0].checked ? 'y' : 'n';
s.allow_multiple_attempt = jQuery("[id$='_cbAllowMultipleAttempt']")[0].checked ? 'y' : 'n';
popC("#add_s");
s.action = id === -1 ? "save" : "update";
s.entity = "survey";
jQuery.postJSON("ajax.aspx", s, function(data) { loadAllSurvey(); });
}
*/

function popO(obj, options) {
    var o = jQuery(obj);
    var opts = _default(options, {});
    if (opts.title != 'undefine' && opts.title != null)
        opts.title = _default(opts.title, '');
    opts.modal = true;
    opts.height = "auto";
    opts.autoOpen = true;
    opts.position = _default(opts.position, ['center', 'top']);
    opts.width = _default(opts.width, 600);
    opts.draggable = false;
    opts.resizable = false;
    jQuery(obj).dialog(opts).dialog("open");
}

function popC(obj) {
    jQuery(obj).dialog("close");
}

function resetForm(form_id_or_obj) {
    var d = jQuery(form_id_or_obj).eq(0);
    jQuery(":text, textarea, :file, :password, input[type='hidden']", d).val("");
    jQuery(":checkbox, :radio", d).each(function() { this.checked = false; });
    jQuery("select", d).each(function() { this.selectedIndex = 0; if (this.onchange != undefined) this.onchange(); });
}
//To clear only fields not hidden fields..used during publish and extend popup
function resetForm_KeptHidden(form_id_or_obj) {
    var d = jQuery(form_id_or_obj).eq(0);
    jQuery(":text, textarea, :file", d).val("");
    jQuery(":checkbox, :radio", d).each(function() { this.checked = false; });
    jQuery("select", d).each(function() { this.selectedIndex = 0; if (this.onchange != undefined) this.onchange(); });
}


/* NEW SCRIPT ENDS HERE*/

/* OLD SCRIPT STARTS FROM HERE */
function toggle_elem(elem_id, status) {
    if (elem_id) {
        var obj = document.getElementById(elem_id)
        if (obj != undefined && obj.style != undefined && obj.style.display != undefined) {
            if (status == 0) {
                obj.style.display = "none";
            } else {
                obj.style.display = "block";
            }
        }
    }
}

function show_hide(elem_id, status) {
    if (status == undefined) {
        status = 1;
    }
    toggle_elem(elem_id, status);
    setMinHeight();
}

var dbg;

function setMinHeight(elem_id, num) {
    elem_id = (elem_id == undefined ? "content" : elem_id);
    num = (num == undefined ? 500 : num);
    var obj = document.getElementById(elem_id);
    if (obj != undefined) {
        dbg = obj;
        var hei = obj.offsetHeight && obj.offsetHeight < num ? num + "px" : "100%";
        obj.style.height = hei;
    } else {
        obj.style.height = num + "px";
    }
    if (obj != undefined) {
        dbg = obj;
        var hei = obj.offsetHeight && obj.offsetHeight <= num ? num + "px" : "100%";
        obj.style.height = hei;
    } else {
        obj.style.height = num + "px";
    }
}

//function resetForm(){
//	if(document.forms[0]){
//		var frm = document.forms[0];
//		var obj;
//		for(i = 0; i < frm.elements.length; i++){
//			obj = frm.elements[i];
//			if(obj.name && obj.name.indexOf("_") == 0){
//				continue;
//			}
//				if(frm.elements[i].type == "image" || frm.elements[i].type == "text" || frm.elements[i].type == "hidden" || frm.elements[i].type == "textarea" || frm.elements[i].type == "radio" || frm.elements[i].type == "checkbox" || frm.elements[i].type == "select"){
//				if((obj.type == "text" || obj.type == "textarea") && obj.value != undefined) 
//					obj.value = "";
//				else if((obj.type == "radio" || obj.type == "checkbox") && obj.checked)
//					obj.checked = false;
//				else if (obj.type == "select" && obj.selectedIndex)
//					obj.selectedIndex = 0;							
//			}
//			
//		}
//		if(document.getElementById("ctl00_ContentPlaceHolder1_logo_img") && document.getElementById("ctl00_ContentPlaceHolder1_logo_img").src != "")
//		document.getElementById("ctl00_ContentPlaceHolder1_logo_img").style.display="none";
//	}
//}

function pre_load(q_num) { }
function post_load() { }

function load_question(num) {
    pre_load(num);
    var p = location.href.toLowerCase().indexOf("preview") >= 0 ? 1 : 0;
    var loc = "NextQuestion.aspx" + window.location.search + "&q=" + num + "&p=" + p;
    var div = document.getElementById("q_area");
    div.innerHTML = "Loading.... ";
    GetResponse(loc, function() {
        var div = document.getElementById("q_area");
        if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete") {
            var resp = xmlHttp.responseText;
            div.innerHTML = resp;
            toggle_elem('btnNext', 1);
            if (resp.indexOf("<script>") > 0) {
                var script = /<script>(.*)<\/script>/.exec(resp);
                if (script && script[1]) {
                    eval(script[1]);
                }
            }
            post_load();
        }
    });
}

function post_HTML_Events(q, opt, qid) {
    q_type = q.split("-")[0];
    cur_q_id = qid;
    cur_q_layout = parseInt(q.split("-")[1]);
    var parent = jQuery("#q_area").eq(0);

    if (q_type == 3) {
        jQuery("#datepicker", parent).datepicker();
    }
    if (q_type == 5) {
        var selOpts = opt.split("\n");
        jQuery("#slider", parent).slider({
            value: 0,
            min: 0,
            max: selOpts.length - 1,
            step: 1,
            slide: function(event, ui) {
                jQuery("#sRate", parent).text(selOpts[ui.value]);
            }
        });
        //jQuery("#slider", parent).removeClass();
        jQuery("#sRate", parent).text(selOpts[jQuery("#slider", parent).slider("value")]);
    }
}

function endSurvey() {
    var div = document.getElementById("base_area");
    var elems = div.getElementsByTagName("INPUT");
    for (var i = 0; i < elems.length; i++) {
        if (elems[i].type == "button") {
            elems[i].style.display = "none";
        }
    }
}



var xmlHttp = null;

function GetXmlHttpObject() {
    try {
        // Firefox, Opera 8.0+, Safari
        if (xmlHttp != undefined) {
            xmlHttp.onreadystatechange = {};
            xmlHttp = null;
        }
        xmlHttp = new XMLHttpRequest();
    } catch (e) {
        //Internet Explorer
        try {
            xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
    }
}

function GetResponse(url, callback) {
    GetXmlHttpObject();
    if (xmlHttp == null) {
        alert("Your browser doesn't support AJAX.");
    } else {
        xmlHttp.onreadystatechange = callback;
        xmlHttp.open("GET", url, true);
        xmlHttp.send(null);
    }
}

function show_error(msg, pos) {
    var str = "<div style='margin: 0px auto; width: 60%;' id='error'>";
    str += "<span style='float: right;'><a href='javascript:void(0);' onclick='show_hide(\"diverror\", 0);'>Close [x]</a></span>"
    str += "<div style='clear: both; margion-bottom: 5px;padding-bottom:5px;'>"
    str += msg;
    str += "</div></div>";
    document.writeln(str);
}

function show_msg(msg, pos) {
    var str = "<div style='margin: 0px auto; width: 60%;' id='msg'>";
    str += "<span style='float: right;'><a href='javascript:void(0);' onclick='show_hide(\"divmsg\", 0);'>Close [x]</a></span>"
    str += "<div style='clear: both; margion-bottom: 5px;padding-bottom:5px;'>"
    str += msg;
    str += "</div></div>";
    document.writeln(str);
}

/*
var dbg = null;
function checkForSubmit(evt){
var e = evt ? evt : window.event;
alert(e);
dbg = e;
var code = e.which ? e.which : e.keyCode;
if(code == 13){
alert("code : " + code);
var obj = e.target ? e.target : e.srcElement;
var elems = obj.parentNode.getElementsByTagName("INPUT");
for(var i = 0; i< elems.length; i++){
if(elems[i].type == "submit"){
//elems[i].onclick();
break;
}
}
if (e && e.preventDefault)
e.preventDefault(); // DOM style
alert("cancelling ... ");
if(window.event) { 
event.cancelBubble = true;
event.returnValue = false;
}
}
return false;
}

function addObjEvent(obj_id, evt_name, func) {
var obj = document.getElementById(obj_id);
if(obj != undefined){
if(obj.addEventListener != undefined){
evt_name = evt_name.replace("on","");
evt_name = evt_name.toLowerCase();
obj.addEventListener(evt_name, func, false);
} else if(obj.attachEvent != undefined){ 
obj.attachEvent(evt_name, func);
}
}
}
*/


function onOtherSelection(tb_name) {
    var obj = document.forms[0][tb_name];
    if (obj != undefined) {
        obj.value = "";
        obj.disabled = true;
    }
}

function onOptionSelection(tb_name) {
    var obj = document.forms[0][tb_name];
    if (obj != undefined) {
        obj.disabled = false;
    }
}

function checkCommentSelection(obj, prefix) {
    var arr = ["tbOption1", "tbOption2", "tbOption3", "tbOption4", "tbOption5", "rbOption5", "rbOtherBox"];
    var sel = obj.options[obj.selectedIndex].value;
    var obj = null;
    var needToReset = sel == "comment" ? true : false;
    for (var i = 0; i < arr.length; i++) {
        obj = document.forms[0][prefix + arr[i]];
        if (obj != undefined) {
            if (needToReset) {
                obj.value = "";
                if (obj.checked) {
                    obj.checked = false;
                }
            }
            obj.disabled = needToReset;
        }
    }
}

function showpop(url) {
    var lwidth = screen.availWidth / 2;
    var lheight = screen.availHeight / 2 + 30;
    var lleft = (screen.availWidth / 2) - (lwidth / 2);
    var ltop = (screen.availHeight / 2) - (lheight / 2);
    var lf = "left=" + lleft + ",width=" + lwidth + ",top=" + ltop + ",height=" + lheight + ",toolbar=no,menubar=no,scrollbars=no,location=no,status=yes,resizable=yes";
    window.open(url, "IntegrationCode", lf);
}

function showpop1(url) {
    var lwidth = 1024;
    var lheight = 800;
    var lleft = (screen.availWidth / 2) - (lwidth / 2);
    var ltop = (screen.availHeight / 2) - (lheight / 2);
    var lf = "left=" + lleft + ",width=" + lwidth + ",top=" + ltop + ",height=" + lheight + ",toolbar=no,menubar=no,scrollbars=no,location=no,status=yes,resizable=yes";
    window.open(url, "IntegrationCode", lf);
}

function showPreviewTemp(obj, sid, w, h, tid) {
    if (obj != null) {
        jQuery(obj).siblings().removeClass("HighlightName");
        jQuery(obj).addClass("HighlightName");
    }

    jQuery(".SurveyInfo").css("display", "block");
    var ifmc = jQuery(".SurveyInfo");
    var ifm = jQuery("#SurveyInfo");
    if (sid != null) {
        jQuery(":input[name='hdnstid']").val(sid);
        jQuery("#SurveyQuestions").css("display", "block");
        ifm.html("<iframe src='temp_Preview.aspx?show=" + sid + "' id='frmPreview' frameborder=0 style='width:" + w + ";height:" + h + "'></iframe>");
    }
    else {
        jQuery(":input[name='hdnstid']").val('');
        jQuery("#SurveyQuestions").css("display", "none");
        //ifm.html(ifmc.eq(0).html());
        jQuery("#tinfo").html(ifmc.eq(0).html());
    }
}
function selected(obj_td) {
    var obj = document.getElementById("ctl00_ContentPlaceHolder1_GridView1");
    if (obj != undefined) {
        var all_as = obj.getElementsByTagName("TR");
        for (var i = 0; i < all_as.length; i++) {
            var a = all_as[i];
            if (a === obj_td) {
                a.className = a.className.indexOf("selectedA") > 0 ? a.className : a.className + " selectedA";
                a.blur();
            } else {
                a.className = a.className.replace("selectedA", "");
            }
        }
    }
}
//used in survey template
function where(obj_collction, prop_name, value) {
    var s = null, ret = null;
    for (var i = 0; i < obj_collction.length; i++) {
        s = obj_collction[i];
        if (s[prop_name] === value) {
            ret = s;
            break;
        }
    }
    return ret;
}

function getCurrentPageUrl() {
    return window.location.href;
}

function getCurrentPageAjaxUrl() {
    return window.location.href.replace(".aspx", "_ajax.aspx");
}

function slideSwitch() {
    var $active = $('#slideshow IMG.active');

    if ($active.length == 0) $active = $('#slideshow IMG:last');

    // use this to pull the images in the order they appear in the markup
    var $next = $active.next().length ? $active.next()
        : $('#slideshow IMG:first');

    // uncomment the 3 lines below to pull the images in random order

    // var $sibs  = $active.siblings();
    // var rndNum = Math.floor(Math.random() * $sibs.length );
    // var $next  = $( $sibs[ rndNum ] );


    $active.addClass('last-active');

    $next.css({ opacity: 0.0 })
        .addClass('active')
        .animate({ opacity: 1.0 }, 1000, function() {
            $active.removeClass('active last-active');
        });
}

/*
$(function() {
setInterval( "slideSwitch()", 5000 );
});
*/

//to set max length in textarea .. used in Questions
function limitText(obj, Num) {
    if (obj.value.length > Num) {
        obj.value = obj.value.substring(0, Num);
    }
}

//HR: 2010-04-02
// OnePageSurvey Scripts starts from here.
var Qs = new Array();
var sep = "_-_"
var sep1 = "___";
var sep2 = "---";
var id = 0;
var temp;
var thankMsg;

function loadStart(surveyid, g) {
    temp = surveyid;
    jQuery.postJSON(my_surveys, { action: "getOnePage", entity: "onepage", surveyid: surveyid, reqType: "ajax" }, function(data) {
        if (data != null) {
            //            jQuery(".SInfo").html(data.closed_msg);
            //            jQuery("#SSInfo").show();
            jQuery("#welcome").eq(0).show();
            if (data.welcome_message.length > 0)
                jQuery("#welcome_msg").eq(0).html(data.welcome_message.replace(/\n/g, "<br />"));
            else
                loadQuestions(surveyid);

            thankMsg = data.thankyou_message;
        }
        else
            loadQuestions(surveyid);
        if (g) {
            jQuery.postJSON(my_surveys, { action: "templateinfo", entity: "onepage", surveyid: surveyid, reqType: "ajax" }, function(data) {
                if (data != null) {
                    jQuery(".SInfo").html(data.Result.replace(/&lt;/g, "<").replace(/&gt;/g, ">"));
                    jQuery("#SSInfo").show();
                }
            });
        }
    });
}
function loadQuestions(surveyid) {
    jQuery("#welcome").eq(0).hide();
    id = _default(surveyid, temp)
    jQuery.postJSON(my_surveys, { action: "listQuestions", entity: "onepage", surveyid: id, reqType: "ajax" }, function(data) {
        Qs = [];
        if (data && data.table && data.table.rows && data.table.rows.length > 0) {
            Qs = objectify(data).table.rows;
            formatOnePageQList();
        }
    });
}

function formatOnePageQList() {
    var ret = "", s = null;
    var fmt = jQuery("#QFormat div").eq(0).outerHTML();
    jQuery("#q_area").empty();
    var ret1 = "", ret2 = "", count = 0;
    var srno = 1;
    for (var i = 0; i < Qs.length; i++) {
        s = Qs[i];
        count += 1;
        ret2 = formatString(fmt
        /*{0}*/, s.qid
        /*{1}*/, s.q_text.replace(/\\'/g, "\'")
        /*{2}*/, ""
        /*{3}*/, "<b>(" + (srno <= Qs.length ? srno++ : 0) + " of " + Qs.length + ")</b>"
        /*{4}*/, s.q_type + "-" + _default(s.layout, "")
			);

        jQuery("#q_area").append(ret2);
        var d = jQuery("#q_area").children("div:last");
        generateAnswer(s, jQuery(".answer_section", d));
    }
    jQuery("#btnSaveAllQs").eq(0).show();
    jQuery("#q_area").show();
}
var IsFreeUser = "True";
function SaveAll() {
    var str = "";
    var d = jQuery("#q_area").eq(0);
    jQuery(".qDivs", d).each(function(data) {
        var postdata = getAllSelectedAnswer(this.id, jQuery("#" + this.id).attr("type"));
        str += this.id + sep1 + postdata + sep2;
        postdata = "";
    });

    var uid = escape(document.getElementById("US_uid__").value);

    jQuery.postJSON("onepagesurvey_ajax.aspx", { surveyid: temp, uid: uid, reqType: "ajax", answer: str }, function(data) {
        if (data && data.msg && data.msg.msg && data.msg.msg.indexOf("error") == "-1") {
            showProgress(data.msg.msg, 5000);
            if (data.IsFreeUser.Result && data.IsFreeUser.Result == "False") {
                IsFreeUser = data.IsFreeUser.Result;
                loadEnd(5000);
                //if (thankMsg != "")
                //   loadEnd(5000);
                //else
                //   loadEnd(0);
            }
            else
                loadEnd(0);
        }
    });
}

function loadEnd(timeout) {
    //Don't show signup banner at the end of survey if its a Pro User Survey.
    jQuery("#btnSaveAllQs").eq(0).hide();
    jQuery("#q_area").eq(0).hide();
    jQuery("#thankyou_msg").eq(0).show();
    var obj = jQuery("#q_area").eq(0);
    if (timeout != undefined && IsFreeUser == "False") {
        if (thankMsg.startsWith("http://")) {
            jQuery("#thankyou_msg").eq(0).html("You will shorly redirect to <b>" + thankMsg + "</b> ");
            obj.delayedCall(function() {
                window.location.href = thankMsg;
            }, timeout);
        }
        else {
            jQuery("#divMsg").eq(0).hide();
            jQuery("#thankyou_msg").eq(0).html(thankMsg);
        }
    }
    else {
        jQuery("#divMsg").eq(0).show();
        jQuery("#powered_by").eq(0).hide();
        jQuery("#sname").eq(0).hide();
    }
}


function loadEnd_old(timeout) {
    jQuery("#btnSaveAllQs").eq(0).hide();
    jQuery("#q_area").eq(0).hide();
    jQuery("#thankyou_msg").eq(0).show();
    var obj = jQuery("#q_area").eq(0);
    if (thankMsg.startsWith("http://")) {
        jQuery("#divMsg").eq(0).show();
        if (timeout != undefined && IsFreeUser == "False") {
            obj.delayedCall(function() {
                window.location.href = thankMsg;
            }, timeout);
        }
    }
    else {
        //delayedCall()
        jQuery("#divMsg").eq(0).hide();
        jQuery("#thankyou_msg").eq(0).html(thankMsg);
        if (timeout != undefined) {
            obj.delayedCall(function() {
                jQuery("#powered_by").eq(0).hide();
                jQuery("#sname").eq(0).hide();
                jQuery("#ltlLogo").hide();

                jQuery("#divMsg").eq(0).show();
                jQuery("#thankyou_msg").eq(0).hide();
            }, timeout);
        }
    }
}

function getAllSelectedAnswer(id, type) {
    if (id && id != "undefined") cur_q_id = id;
    if (type && type != "undefined") q_type = type.split("-")[0];
    if (type && type != "undefined") cur_q_layout = type.split("-")[1];
    var ret = "";
    var arr = null;
    switch (q_type) {
        case "comment":
        case "0": //comment box
        case "3": //datepicker
            //case "4"://file upload
            ret = jQuery("#" + cur_q_id + " :input[name='t" + cur_q_id + "']").eq(0).val().replace(/'/g, "\\'");
            break;
        case "check":
        case "1": //Multiplec choice - multiple answer checkbox // listbox
            if (cur_q_layout == 1)// list box
                jQuery("#" + cur_q_id + " :input[name='s" + cur_q_id + "']").each(function() {
                    ret += jQuery(this).val() + ",";
                });
            else  //for both old type 'check' and cur_q_layout == 0 //checkbox
                jQuery("#" + cur_q_id + " input:checkbox:checked").each(function() {
                    ret += jQuery(this).val() + ",";
                });
            ret = ret.substring(0, ret.length - 1);
            if (ret.indexOf("-1") != -1)
                ret += '&txtOther=' + escape(jQuery("#q_area :input[name='txtOther" + cur_q_id + "']").eq(0).val().replace(/'/g, "\\'"));
            break;
        case "radio":
        case "2": //Multiplec choice - single answer 
            if (cur_q_layout == 1) // dropdown
                ret = jQuery("#" + cur_q_id + " :input[name='s" + cur_q_id + "']").val();
            else
                ret = jQuery("#" + cur_q_id + " input:radio:checked").eq(0).val();
            if (ret && ret.indexOf("-1") != -1)
                ret += '&txtOther=' + escape(jQuery("#q_area :input[name='txtOther" + cur_q_id + "']").eq(0).val().replace(/'/g, "\\'"));
            break;
        case "5": //rating
            ret = jQuery("#" + cur_q_id + " #sRate").eq(0).text();
            break;
        case "6": //"Multiple TextBox with labels"
        case "9": //"Demographic info"
            jQuery("#" + cur_q_id + " input:text").each(function() {
                ret += jQuery(this).val().replace(/'/g, "\\'") + sep;
            });
            break;
        case "7": // Matrix for single selection
            jQuery("#" + cur_q_id + " input:radio:checked").each(function() {
                ret += jQuery(this).attr('id') + sep;
            });
            break;
        case "8": // Matrix for multiple selection
            jQuery("#" + cur_q_id + " input:checkbox:checked").each(function() {
                ret += jQuery(this).attr('id') + sep;
            });
            break;
        default:
            ret = "";
            break;
    }
    if (!(ret) || ret == "null") ret = "";
    //alert(ret);
    return ret;
}
// OnePageSurvey Scripts ends here.

// plan popup scripts start here
function showPlan() {
    popO('#divChoosePlan', { title: 'Plan Details', width: 850 });
    jQuery("[id$='_ddlPlan']").val(1);
}

function confirmPlan(Current_url, planid) {
    planid = _default(planid, "");
    if (Current_url.indexOf("?") != -1)
        Current_url = Current_url.split("?")[0];
    if (planid == "") {
        showError("You must have to select plan");
        return;
        //window.location.href = Current_url.replace("price", "signup");
    }

    var url = ""
    var d = jQuery("#divChoosePlan").eq(0);
    var promo = _default(jQuery("#txtPromo").eq(0).val(), "");
    //var autorenew = jQuery("#chkautorenew").get(0).checked ? 1 : 0;
    //var id = _default(jQuery("input:checked", d).val(), 'none');
    //if (id == "none") { showError("You must have to choose billing period"); return; }
    jQuery.postJSON(my_surveys, { entity: "encrypt", action: "encrypt", planid: planid, promo: promo }, function(data) {
        if (data && data.error) { showError(data.error); return; }
        if (data && data.pid) {
            if (Current_url.indexOf("price") != "-1") {
                //        url = Current_url.replace("account", "PlanWizard") + "?pid=" + jQuery("[id$='_ddlPlan']").val();
                url = Current_url.replace("price", "signup") + "?pid=" + data.pid.Result;
            }
            else if (Current_url.indexOf("my_surveys") != "-1")
                url = Current_url.replace("my_surveys", "PlanWizard") + "?pid=" + data.Result + "&promo=" + promo;
            //        url = Current_url.replace("my_surveys", "PlanWizard") + "?pid=" + jQuery("[id$='_ddlPlan']").val();
            else
            //url = Current_url + "?pid=" + data.pid.Result + (data.promo.Result != "" ? "&promo=" + data.promo.Result : "") + "&autorenew=" + data.autorenew.Result;
                url = Current_url + "?pid=" + data.pid.Result + (data.promo.Result != "" ? "&promo=" + data.promo.Result : "");
            window.location.href = url;

        }
    });

}
function setBtnTitle() {
    if (jQuery("[id$='_ddlPlan']").val() == 1) {
        jQuery("#btnUpgrade").hide();
        jQuery("#divFree").show();
        jQuery("#divProM").hide();
        jQuery("#divProQ").hide();
        jQuery("#divUnl").hide();
    }
    else {
        jQuery("#btnUpgrade").show();
        if (jQuery("[id$='_ddlPlan']").val() == 2) {
            jQuery("#divProM").show();
            jQuery("#divProQ").hide();
            jQuery("#divFree").hide();
            jQuery("#divUnl").hide();
        }
        else if (jQuery("[id$='_ddlPlan']").val() == 3) {
            jQuery("#divProQ").show();
            jQuery("#divProM").hide();
            jQuery("#divFree").hide();
            jQuery("#divUnl").hide();
        }
        else if (jQuery("[id$='_ddlPlan']").val() == 4) {
            jQuery("#divUnl").show();
            jQuery("#divProM").hide();
            jQuery("#divProQ").hide();
            jQuery("#divFree").hide();
        }
    }
}

//plan popup scripts ends here

//payment history script here
function paymentHistory(upid) {
    jQuery.postJSON("account_ajax.aspx", { entity: "history", upid: upid }, function(data) {
        if (data && data.error) { showError(data.error); return; }
        var rows = [];
        var cols = [];
        rows = objectify(data).table.rows;
        cols = objectify(data).table.cols;
        var d = jQuery("#divFormat").eq(0).html();
        var ret = "";
        ret += "<td class='th2'>Payment Gateway</td>";
        ret += "<td class='th2'>Transaction Id</td>";
        ret += "<td class='th2'>Paid On</td>";
        ret += "<td class='th2'>Amount</td>";
        ret += "<td class='th2'>Discount</td>";
        ret += "<td class='th2'>Total Pay</td>";

        ret = "<tr>" + ret + "</tr>";

        for (var i = 0; i < rows.length; i++) {
            ret += "<tr><td>" + rows[i].PaymentGateway + "</td><td>" + rows[i].paypal_trans_id + "</td><td>" + rows[i].paiddate + "</td><td>$" + rows[i].cost + "</td><td>" + rows[i].DiscPert + "% </td><td>$" + rows[i].amount + "</td> "
        }

        ret = "<table width='100%' cellpadding='2'>" + ret + "</table>";

        jQuery("#divPH").html(ret);
        popO("#divPH", { title: "Payment History", width: 700 });
    });
}


/* my_surveys page.. template script start*/
var cur_Q = 0;
var QAs = [];
var sid = "";
var SurveyInfo;
var thnkMsg = "";
var thankingMessage = "";
function ShowStep(tid, obj) {
    jQuery("#SurveyQuestions").html(jQuery(".SurveyQuestions").html()).show();
    jQuery("#q_area1").hide();
    jQuery("#tinfo").show();
    jQuery("#A2").attr("class", "");
    jQuery("#A1").attr("class", "active");
    jQuery("#divBtn2").hide();
    jQuery("#thnx").hide();
    jQuery("#thnx1").hide();
    jQuery(":input[name='hdnstid']").val(tid);
    jQuery("#btnNextQ").attr("value", "Start");
    jQuery("#divBtn").show();
    jQuery("#btnNextQ").show();
    jQuery("#divReport2").show();
    jQuery("#tinfo").css("color", "black");
    jQuery(obj).siblings().removeClass("HighlightName");
    jQuery(obj).addClass("HighlightName");
    jQuery.postJSON(my_surveys, { surveyid: tid, userid: "38", action: "info", entity: "answer", reqType: "ajax" }, function(data) {
        if (data != undefined && data.s_info && data.q_info) {
            jQuery("#tinfo").html('');
            SurveyInfo = data.s_info;
            QAs = objectify(data.q_info).table.rows;
            var msg = SurveyInfo.welcome_message.replace(/\n/g, "<br />");
            if (msg && msg.length > 0) {
                jQuery("#tinfo").html(msg);
                jQuery("#tinfo").css("color", "#EF0EA6");
                jQuery("#tqinfo").hide();
            }
            else {
                jQuery("#tqinfo").show();
                NextQue();
            }
            thnkMsg = SurveyInfo.thankyou_message;

            cur_Q = 0;
        }
    });
    jQuery("input:submit,input:reset,input:button").button();
}
function NextQue() {
    jQuery("#tinfo").css("color", "black");
    var q = QAs[cur_Q];
    if (cur_Q < QAs.length) {
        jQuery("#btnNextQ").attr("value", "Next");
        jQuery("#tqinfo").show();
        jQuery("#tqinfo").html('<b>(Question ' + (cur_Q + 1) + ' of ' + QAs.length + ')</b> ' + q.q_text.replace(/\\'/g, "'") + '<br />');
        generateAnswer(q, jQuery("#tinfo"));
        cur_Q++;
    }
    else if (cur_Q > QAs.length) {
        jQuery("#tinfo").html(jQuery("#attemptST").html());
        jQuery("#divBtn").hide();
        jQuery("#divBtn2").hide();
        jQuery("#tqinfo").hide();
        jQuery(".HighlightName").removeClass();
        jQuery("#divReport2").hide();
        cur_Q = 0;
    }
    else if (cur_Q = QAs.length) {
        cur_Q++;
        jQuery("#btnNextQ").attr("value", "Finish");
        jQuery("#tqinfo").hide();
        jQuery("#tinfo").css("color", "#EF0EA6");
        if (thnkMsg) {
            jQuery("#tinfo").html(thnkMsg);
        }
        else {
            jQuery("#tinfo").html(jQuery("#attemptST").html());
            jQuery("#divBtn").hide();
            jQuery("#divBtn2").hide();
            jQuery(".HighlightName").removeClass();
            jQuery("#divReport2").hide();
            jQuery("#SurveyQuestions").hide();
        }
    }
}
function ShowDirectG() {
    jQuery("#A2").attr("class", "");
    jQuery("#A1").attr("class", "active");
    jQuery("#divBtn").show();
    jQuery("#q_area1").hide();
    jQuery("#divBtn2").hide();
    ShowStep(jQuery(":input[name='hdnstid']").val(), jQuery(".HighlightName").eq(0));
}
function ShowOnePageG() {
    jQuery("#SurveyQuestions").html(jQuery(".SurveyQuestions").html()).show();
    jQuery("#btnNextQ").hide();
    jQuery("#A2").attr("class", "active");
    jQuery("#A1").attr("class", "");
    var tid = jQuery(":input[name='hdnstid']").val();
    jQuery("#btnAllQ").attr("value", "Start");
    jQuery.postJSON(my_surveys, { action: "getOnePage", entity: "onepage", surveyid: tid, reqType: "ajax" }, function(data) {
    if (data) {
        jQuery("#divBtn2").show();
            if (data.welcome_message.length > 0) {
                jQuery("#tinfo").eq(0).html(data.welcome_message.replace(/\n/g, "<br />"));
                jQuery("#tinfo").css("color", "#EF0EA6");
                jQuery("#tqinfo").hide()
                jQuery("#btnNextQ").hide();
                           }
            else {
                AllQue(jQuery(":input[name='hdnstid']").val());
            }
            thankingMessage = data.thankyou_message;
            if (thankingMessage)
                jQuery("#thnx").html(thankingMessage);
            else
                jQuery("#thnx").html('');
            jQuery("#thnx1").hide();
        }
    });
}
var Qs1 = new Array();
var FinishPress = "0";
function AllQue(tid) {
    jQuery("#tqinfo").hide();
    jQuery("#btnAllQ").show();
    jQuery("#tinfo").css("color", "black");
    if (FinishPress == "0") {
        jQuery("#q_area1").show();
        jQuery("#tinfo").hide();
        jQuery("#btnAllQ").attr("value", "Finish");
        var tid = jQuery(":input[name='hdnstid']").val();
        jQuery.postJSON(my_surveys, { action: "listQuestions", entity: "onepage", surveyid: tid, reqType: "ajax" }, function(data) {
            Qs1 = [];
            if (data && data.table && data.table.rows && data.table.rows.length > 0) {
                Qs1 = objectify(data).table.rows;
                formatOnePageQList1();
                FinishPress = FinishPress == "0" ? "1" : "0";
            }
        });
    }
    else if (FinishPress == "1") {
        FinishPress = FinishPress == "0" ? "1" : "0";
        jQuery("#q_area1").hide();
        jQuery("#divBtn2").hide();
        if (thankingMessage != "") {
            jQuery("#thnx1").show();
            jQuery("#thnx").show();
            jQuery("#thnx").css("color", "#EF0EA6");
        }
        else
            End();
    }
}

function formatOnePageQList1() {
    var ret = "", s = null;
    var fmt = jQuery("#QFormat1 div").eq(0).outerHTML();
    jQuery("#q_area1").empty();
    var ret1 = "", ret2 = "", count = 0;
    var srno = 1;
    for (var i = 0; i < Qs1.length; i++) {
        s = Qs1[i];
        count += 1;
        ret2 = formatString(fmt
        /*{0}*/, s.qid
        /*{1}*/, s.q_text.replace(/\\'/g, "\'")
        /*{2}*/, ""
        /*{3}*/, "<b>(" + (srno <= Qs1.length ? srno++ : 0) + " of " + Qs1.length + ")</b>"
        /*{4}*/, s.q_type + "-" + _default(s.layout, "")
			);

        jQuery("#q_area1").append(ret2);
        var d = jQuery("#q_area1").children("div:last");
        generateAnswer(s, jQuery(".answer_section1", d));
    }
    jQuery("#q_area1").show();
}

function End() {
    jQuery("#tinfo").show();
    jQuery("#tinfo").css("color", "black");
    jQuery("#tinfo").html(jQuery("#attemptST").html());
    jQuery("#thnx1").hide();
    jQuery("#thnx").hide();
    jQuery(".HighlightName").removeClass();
    jQuery("#divReport2").hide();
    jQuery("#SurveyQuestions").hide();
    jQuery("#tqinfo").hide();
    
}
/* my_surveys page.. template script end*/


function HideMessage() {
    jQuery.postJSON(my_surveys, { action: "hideMsg", entity: "other", reqType: "ajax" }, function(d) {
    jQuery("[id$='_divSampleSurvey']").hide();
     });


}