$(document).ready(function() {

		
		if ('div#fptabs'){
			
		$('#fptabs').tabs();
		}
    var pathname = ""+window.location;
    var baseURL = extractURL(pathname);
    var params = jQuery.param.querystring();
    var cancel = "false";
    if(params.length > 0)
    {
        var queryString = jQuery.deparam.querystring();
        var purchaseToken = queryString.token;
        var payerId = queryString.PayerID;
            cancel = queryString.c;
        if(cancel == "true")
        {
            window.location = baseURL;
        }
    }

    $('div#wrapper').show();
    $('html').addClass('loaded');
    var nliHolder;
    
    var buildType = 'normal';
    var editSurvey = '';

    var completionStatus = [];
    var apiServices;
    var apiKeyGlob;

    var sessionID;
    var userRole;

    var usrCreditBalance;

    var prefill = "";

    function extractURL(pathname){
        var url = "";
        //Hack to set baseURL
        //Since we enabled permalink this wont work in production
        //when you login to mpoll
        var urlArr = pathname.split("/");
        if(urlArr.length > 7)
        {
            $.each(urlArr, function(i, pname){
                if (i == 0){
                    url = pname;
                }
                if (i != 0 && i != urlArr.length-1)
                {
                    url = url+"/"+pname;
                }
            });
        }
        else
        {
            url = location.protocol+'//'+location.host;
        }
        compurl = url+"/";

        return compurl;
    }
    
    //URL VARIABLES//////////////////////////////////////////////////
    var baseURL = extractURL(pathname);
    var forcenohttperror = '&_forcenohttperror=true';
	var URLappendage = '/REST/?'+forcenohttperror+'&output=jsoncallback&callback=?'
    
    var LoginUser = baseURL+'LoginUser'+URLappendage;
	var RegisterUser = baseURL+'RegisterUser'+URLappendage;
	var LostPassword = baseURL+"LostPassword"+URLappendage;
	var GetUserData = baseURL+"GetUserData"+URLappendage;
	var UpdateUser = baseURL+"UpdateUser"+URLappendage;
	var ChangePassword = baseURL+"ChangePassword"+URLappendage;
	var GetActiveSurveys = baseURL+"GetActiveSurveys"+URLappendage;
	var DeleteSurvey = baseURL+"DeleteSurvey"+URLappendage;
	var DistributeSurvey = baseURL+"DistributeSurvey"+URLappendage;
	var CreateNewSurvey = baseURL+"CreateNewSurvey"+URLappendage;
	var SetSurveyTheme = baseURL+"SetSurveyTheme"+URLappendage;
	var AddSurveyQuestion = baseURL+"AddSurveyQuestion"+URLappendage;
	var GetSurveyDetails = baseURL+"GetSurveyDetails"+URLappendage;
	var GetSurveyTheme = baseURL+"GetSurveyTheme"+URLappendage;
	var GetQuestions = baseURL+"GetQuestions"+URLappendage;
	var GetAnswers = baseURL+"GetAnswers"+URLappendage;
	var AddAnswer = baseURL+"AddAnswer"+URLappendage;
	var UpdateSurvey = baseURL+"UpdateSurvey"+URLappendage;
	var UpdateSurveyQuestion = baseURL+"UpdateSurveyQuestion"+URLappendage;
	var UpdateAnswer = baseURL+"UpdateAnswer"+URLappendage;
	var DeleteSurveyQuestion = baseURL+"DeleteSurveyQuestion"+URLappendage;
	var DeleteAnswer = baseURL+"DeleteAnswer"+URLappendage;
	var ReuseSurvey = baseURL+"ReuseSurvey"+URLappendage;
	var GetSurveyResponses = baseURL+"GetSurveyResponses"+URLappendage;
	var UploadLogo = baseURL+"UploadLogo/REST/?'+forcenohttperror+'&output=jsoncallback&_forcetext=true";
    var GetTotalCreditAmount = baseURL+"GetTotalCreditAmount"+URLappendage;
    var GetConfigValues = baseURL+"GetConfigValues"+URLappendage;
    var GetGlobalConfigurations = baseURL+"GetGlobalConfigurations"+URLappendage;
    var UpdateGlobalConfigurations = baseURL+"UpdateGlobalConfigurations"+URLappendage;
    var GetSurveyPricing = baseURL+"GetSurveyPricing"+URLappendage;
    var SetPricingModel = baseURL+"SetPricingModel"+URLappendage;
    var GetSurveyUsers = baseURL+"GetSurveyUsers"+URLappendage;
    var GetUserDetails = baseURL+"GetUserDetails"+URLappendage;
    var UpdateSurveyUser = baseURL+"UpdateSurveyUser"+URLappendage;
    var GetUserSurveyUsage = baseURL+"GetUserSurveyUsage"+URLappendage;
    var GetDetailedUserSurveyUsage = baseURL+"GetDetailedUserSurveyUsage"+URLappendage;
    var GetUserCreditsUsage = baseURL+"GetUserCreditsUsage"+URLappendage;
    var GetPurchaseHistory = baseURL+"GetPurchaseHistory"+URLappendage;
    var GetCreditBalance = baseURL+"GetCreditBalance"+URLappendage;
    var GetUserBillingAddress = baseURL+"GetUserBillingAddress"+URLappendage;
    var GetUserPurchaseHistory = baseURL+"GetUserPurchaseHistory"+URLappendage;
    var GetDistributedSurveys = baseURL+"GetDistributedSurveys"+URLappendage;
    var GetSurveysSentStatus = baseURL+"GetSurveysSentStatus"+URLappendage;
    var GetCreditUsage = baseURL+"GetCreditUsage"+URLappendage;
    var GetVouchers = baseURL+"GetVouchers"+URLappendage;
    var GetVoucherDetails = baseURL+"GetVoucherDetails"+URLappendage;
    var CreateVoucher = baseURL+"CreateVoucher"+URLappendage;
    var UpdateVoucher = baseURL+"UpdateVoucher"+URLappendage;
    var DeleteVoucher = baseURL+"DeleteVoucher"+URLappendage;
    var RedeemVoucher = baseURL+"RedeemVoucher"+URLappendage;
    var UpdateUserSurveyPricing = baseURL+"UpdateUserSurveyPricing"+URLappendage;
    var GetCurrencyRates = baseURL+"GetCurrencyRates"+URLappendage;
    var ContactUs = baseURL+"ContactUs"+URLappendage;
    var GetUserPricing = baseURL+"GetUserPricing"+URLappendage;
    var TogglePricingView = baseURL+"TogglePricingView"+URLappendage;
    var UpdateQuestionPosition = baseURL+"UpdateQuestionPosition"+URLappendage;
    var CheckUserSession = baseURL+"CheckUserSession"+URLappendage;
    var ParseCsvMsids = baseURL+"ParseCsvMsids/REST/?'+forcenohttperror+'&output=jsoncallback&_forcetext=true";
    var ExportCsv = baseURL+"Export"+URLappendage;
    var GenerateAuthKey = baseURL+"GenerateAuthKey"+URLappendage;
    var GetUserApplicationKeys = baseURL+"GetUserApplicationKeys"+URLappendage;
    var GetKeyData = baseURL+"GetKeyData"+URLappendage;
    var AddAnswerTemplate = baseURL+"AddAnswerTemplate"+URLappendage;
    var GetTemplateAnswers = baseURL+"GetTemplateAnswers"+URLappendage;
    var DeleteTemplateAnswer = baseURL+"DeleteTemplateAnswer"+URLappendage;
    var UpdateTemplateAnswerPosition = baseURL+"UpdateTemplateAnswerPosition"+URLappendage; 
    var AddTemplateAnswers = baseURL+"AddTemplateAnswers"+URLappendage;    
    var DeleteApplicationKey = baseURL+"DeleteApplicationKey"+URLappendage;
    var SetNewSurveyTheme = baseURL+"SetNewSurveyTheme"+URLappendage;
    var SendTestSurvey = baseURL+"SendTestSurvey"+URLappendage;
    var UpdateSurveyAttribute = baseURL+"UpdateSurveyAttribute"+URLappendage;
    var GetPublishedSurveys = baseURL+"GetPublishedSurveys"+URLappendage;
    var UpdateEventbriteApi = baseURL+"UpdateEventbriteApi"+URLappendage;
    var GetEventbriteEvents = baseURL+"GetEventbriteEvents"+URLappendage;
    var ImportEventContacts = baseURL+"ImportEventContacts"+URLappendage;
    var GetPublicSurveyUrl = baseURL+"GetPublicSurveyUrl"+URLappendage;
    var GetPublicSurveys = baseURL+"GetPublicSurveys"+URLappendage;
    
    function checkUserSession()
    {
        var logined = getCookieDetails('login');
        var sessionId = getCookieDetails('mpoll_cookie');
        if(logined == "true")
        {
            $.getJSON(CheckUserSession, {s: sessionId}, function(res){
                if(res.CheckUserSession.login == 'false')
                {   
                    logOut();
                }
            });
        }
    }
    //Check User session
    checkUserSession();
    
    var userfullname = getCookieDetails('user_fullname');
    if(userfullname)
    {
        $('#longinedUserName').html(userfullname);
    }
    
    $('#longinedUserName').click(function(){
        $('#tabs').tabs( 'select' , 3);
    });
    
    if($('#register')){
        $('#register').attr("action", LoginUser);
    }
//Random Message Madness
    function randomMsg() {
        var variable_messages=  [
    '<img src="images/loading.gif" alt="loading..." /><h1>Consulting Ye Olde Database...</h1>',
    '<img src="images/loading.gif" alt="loading..." /><h1>Engineers are Binarising Your Request...</h1>',
    '<img src="images/loading.gif" alt="loading..." /><h1>Supercharging Electrons...</h1>',
    '<img src="images/loading.gif" alt="loading..." /><h1>Punching the Cards...</h1>',
    '<img src="images/loading.gif" alt="loading..." /><h1>The Gears are Turning...</h1>',
    '<img src="images/loading.gif" alt="loading..." /><h1>Containing Excitement...</h1>',
    '<img src="images/loading.gif" alt="loading..." /><h1>Holding Your Horses...</h1>',
    '<img src="images/loading.gif" alt="loading..." /><h1>Warming Up Transistors...</h1>',
    '<img src="images/loading.gif" alt="loading..." /><h1>Preparing Life Changing Experience...</h1>',
    '<img src="images/loading.gif" alt="loading..." /><h1>Deploying Paradigm Shift...</h1>'];
        var randomnum = Math.floor(Math.random()*10);
        return variable_messages[randomnum];
    }


// Block UI Styling.
$.blockUI.defaults = {
    // styles for the message when blocking; if you wish to disable
    // these and use an external stylesheet then do this in your code:
    // $.blockUI.defaults.css = {};
    css: {
        padding:        '20px 20px 20px 20px',
        margin:         0,
        width:          '30%',
        top:            '20%',
        left:           '35%',
        textAlign:      'center',
        color:          '#fff',
        backgroundColor:'#444',
        cursor:         'default',
        //'font-size': 'normal',        
        '-webkit-border-radius': '10px',
        '-moz-border-radius':    '10px'
    },
    overlayCSS:  {
        backgroundColor:'#fff',
        opacity:        '0.8'
    },
    baseZ: 1000,
    centerX: true,
    centerY: true,
    allowBodyStretch: true,
    constrainTabKey: true,
    fadeIn:  50,
    fadeOut:  300,
    timeout: 0,
    showOverlay: true,
    focusInput: true,
    applyPlatformOpacityRules: true,
    onUnblock: null,
    quirksmodeOffsetHack: 4
};


//GENERAL FUNCTIONS/////////////////////////////////////////////////////////////////////////////////////
function hexColors(targetCols){
	var rgbString = targetCols;
	var parts;
	if(rgbString.indexOf('#') === 0) {
		newStr = rgbString.replace(/#/, '');
		return newStr;
	}
	
	parts = rgbString.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
	parts.splice(0,1);
	for (var i = 0; i < 3; ++i) {
	    parts[i] = parseInt(parts[i]).toString(16);
	    if (parts[i].length == 1) parts[i] = '0' + parts[i];
	}
	var hexString = parts.join(''); // "0070ff"

	return hexString;
}

function deleteSurvey(surveyID){
	var targetID = '#'+$('.blockUI').parent().attr('id');
		$.getJSON(DeleteSurvey, { s: sessionID, sid: surveyID }, function(json){
			    if (json.error){
                	$(targetID).unblock();
                    miniErrors(targetID, json);
                } else {
                	$('#surveyRow_'+surveyID).remove();
		            $(targetID).unblock();
                }
		})
}

function logOut(){
	deleteCookie('mpoll_cookie');
    deleteCookie('user_role');
    deleteCookie('free_user');
    deleteCookie('survey_pricing_id');
    deleteCookie('login');
    window.location.href=baseURL;
}

//ALERT BOX HANDLERS///////////////////////////////////////////////////////////////////////////////////

        var clicktocontinue = '<div id="continue">click here to continue</div>';        
        var olclicktocontinue = '<div id="ol_continue">click here to continue</div>';
        
		$('div#continue').live('click', function(){
		    $('div#register_box').unblock();
            Recaptcha.reload();
            return false;
		});

		$('div#ol_continue').live('click', function() {
		    $($(this).parent().parent()).unblock();
            var parentId = $(this).parent().parent().attr('id');
            $('#'+parentId).removeClass('heightbig');
		    if(parentId == 'register_box')
		    {
    			$('a#login_act_btn').click();
		    }
			if (parentId == 'userpassword')
            {
				$('input.passwd').val('');
			}	
			if (parentId == 'thedistributor')
            {
			    //$('textarea#msids').val('');
				//$('textarea#message').val('');
			}
			if(parentId == 'distributeBox')
            {
                $('#tabs').tabs( 'select' , 3); 
            }
			if ($(this).hasClass('op_success')){	
				$.unblockUI();
			}
		    if(parentId == 'buyCreditsMore')
		    {
			    window.location.href=baseURL;
		    }
            
		    return false;
		});

  
		function miniErrors(targetDiv, theMessage) {
			var targetWidth = '70%';
			var continueType = olclicktocontinue;
            var msgId = theMessage.error_code;
            var msg = theMessage.error;
            if(msg == undefined)
            {
                msg = theMessage;
            }
            if(msgId == 'ERROR_NOT_LOGGED_IN')
            {
                $(targetDiv).block({css: {color: '#f42c52', width:targetWidth },message:msg+'<div id="sessionTimeOut">click here to continue</div>'});
            }
            else
            {
    			if (targetDiv == 'div#register_box'){
			        continueType = clicktocontinue;		
			    }
			    $(targetDiv).block({css: {color: '#f42c52', width:targetWidth },message:msg+continueType});
                $(targetDiv).removeClass('height');
            }
		}
        $('div#sessionTimeOut').live('click', function(){
            logOut();
        });

  //COOKIE HANDLERS///////////////////////////////////////////////////////////////////////////////////
        var cookieoptions = { path: '/', expires: 99 };

            function deleteCookie(cookieName){ //deletes cookie
                $.cookie(cookieName, null, cookieoptions);
            }

            function createCookie(cookieName, cookieID){
                        $.cookie(cookieName, cookieID, cookieoptions);
            }

            function getCookieDetails(cookieName){
                        return $.cookie(cookieName);
                        //return sessionID;
            }

            function getUserCookieDetails(){
                        var userEmail = $.cookie(USER_DETAIL_COOKIE);
                        return userEmail;
            }
  //LOGIN, REGISTRATION & //////////////////////////////////////////////////////////////////////////////////////
  function nliLoaded(){ // to load if not logged in / logged out.
    	var blockTarget;
		$('html').toggleClass("notloggedin");
        $('div#wrapper').show();
        
        $('#logindiv a').live('click', function(){
			var correct_message;
        	if ($(this).attr('id')=='forgot_password_btn'){
        		correct_message = $('#forgot_password_box');
        	}
        	if ($(this).attr('id')=='login_act_btn'){
        		correct_message = $('#login_box');
        	}
        	$.blockUI({    css: {
        							cursor:'default',
        						    color: '#444',
        							backgroundColor:'#fff',
        							width: '300px'
							    },
							overlayCSS:  {
						        backgroundColor:'#444',
						        opacity:        '0.8'
						    },
							message: correct_message,
							timeout: 0,
							fadeIn:  0
						});
        })
        
        $('a.cancel').click(function(){
        	$.unblockUI();
        })
        
        function regRequest(formData, jqForm, options) {
			$('div#register_box').block({message:"<img src=\"imgs/loader_small.gif\" alt=\"loading...\" /><h4><br/></h4>"});
		}

        function processReg(data) { //determines what to display when user is registering.
                if (data.error){
                	$('div#register_box').unblock();
                	miniErrors('div#register_box', data);
                } else {
                	$('div#register_box').unblock(); 
                    $('div#register_box').block({css: {color: '#25c058'},message:"You have been successfully registered."+olclicktocontinue});
                    $('div#register_box .regularfield').val('');
                }
        }

        function LostPasswordRequest(formData, jqForm, options) {
			$('div#forgot_password_box').block({message:"<img src=\"imgs/loader_small.gif\" alt=\"loading...\" /><h4><br/></h4>"});
		}

        function processLostPassword(data) { //determines what to display when user is registering.
                if (data.error){
                	$('div#forgot_password_box').unblock();
                	miniErrors('div#forgot_password_box', data);
                } else {
                	$('div#forgot_password_box').unblock(); 
                    $('div#forgot_password_box').block({css: {color: '#25c058'},message:"Your password has been emailed to you."+olclicktocontinue});
                    $('div#ol_continue').addClass('op_success');
                    $('div#forgot_password_box .regularfield').val('');
                }
        }

        function loginRequest(formData, jqForm, options) {
                        $('div#login_box').block({message:"<img src=\"imgs/loader_small.gif\" alt=\"loading...\" /><h4><br/></h4>"});
        }
            
        function processLogin(data) { //determines what to display when user is logging in.
                if (data.error){
                	$('div#login_box').unblock();
                    miniErrors('form#login', data);
                } else {
		             $('div#login_box').unblock();
		              	$.unblockUI();
                		createCookie('mpoll_cookie', data.LoginUser.sessionid); //create a cookie
                            createCookie('user_role', data.LoginUser.user_role_id);
                            createCookie('free_user', data.LoginUser.free_user);
                            createCookie('survey_pricing_id', data.LoginUser.survey_pricing_id);
                            createCookie('user_fullname', data.LoginUser.name);
                            $('#longinedUserName').html(data.LoginUser.name);
                            createCookie('login', 'true');
		                	liContents();
                }
            }

                var RegFormOptions = { //These options are fed into the Registration ajaxSubmit function.
                    url: RegisterUser,
                    dataType:  'jsonp',
                    success:   processReg,
                    beforeSubmit:  regRequest
                };

                var LostPasswordOptions = { //These options are fed into the Login ajaxSubmit function.
                    url:  LostPassword,
                	dataType:  'jsonp',
                    success:   processLostPassword,
                    beforeSubmit:  LostPasswordRequest
                };
                
                var LoginFormOptions = { //These options are fed into the Login ajaxSubmit function.
                    url:  LoginUser,
                	dataType:  'jsonp',
                    success:   processLogin,
                    beforeSubmit:  loginRequest
                };                

                var r = $("#register").validate({
                    submitHandler: function(form) {
                        $(form).ajaxSubmit(RegFormOptions);
                    }
                });

				var r = $("#lost_pw").validate({
                    submitHandler: function(form) {
                        $(form).ajaxSubmit(LostPasswordOptions);
                    }
                });

                var l = $('#login').validate({
                    submitHandler: function(form) {
                        $(form).ajaxSubmit(LoginFormOptions);
                    }
                });

        $('div#wrapper').show();
    }
/////////////////////////////////////////////////////////////////////////////////////////////////////
//LOGGED IN/////////////////////////////////////////////////////////////////////////////////////////
function activateLogOut(){
        $('#logout').click(function(){
			logOut();
        })
}

function CreateActivateTabs(){
		var docURL = baseURL+"contents/";
		
	    function prepListing(){
            $.blockUI();
        }

        function displayListing(xml) {
            $(xml).find('filename').each(function(index){
                if($(this).attr('title') == 'Admin')
                {
                    if(userRole == 1)
                    {
                        $('div#tabs > ul').append('<li class="'+$(this).attr('title')+'_btn"><a title="'+$(this).attr('title')+'" href="'+docURL+$(this).attr('name')+'">'+$(this).attr('title')+'</a></li>');
                    }
                }
                else
                {
                    $('div#tabs > ul').append('<li class="'+$(this).attr('title')+'_btn"><a title="'+$(this).attr('title')+'" href="'+docURL+$(this).attr('name')+'">'+$(this).attr('title')+'</a></li>');
                }
            });
            $('div#tabs').tabs({
                load: function(event, ui) {
                    if(ui.index == 8)
                    {
                        loadGlobalConfigurations();
                    }
                    if(ui.index == 7)
                    {
                        loadAPISetup();
                    }
                    if(ui.index == 6)
                    {
                        loadHelp();
                    }
                    if(ui.index == 5)
                    {
                        loadUserReports();
                    }
                    if(ui.index == 4)
                    {
                        buycreditsLoad();
                    }
                    if(ui.index == 3)
                    {
                        managementLoad();
                    }
                    if (ui.index == 2)
                    {
                            distributorLoad();
                    }
                    if(ui.index == 1)
                    {
                        builderLoad(buildType);
                    }
                    if(ui.index == 0)
                    {
                        homeLoad();
                    }
                }
            });
		    $('div#tabs > ul').after('<div class="clearer"></div>');
            //Hiding Account Tab
            $('div#tabs > ul li.Account_btn').hide();
        }

        function loadListing() {
            $.ajax({
                url: baseURL+"xml/sections.xml",
                dataType: "xml",
                success: displayListing,
                before: prepListing
            })
        }

        loadListing();
}

function liContents(){
	sessionID = getCookieDetails('mpoll_cookie'); // sets the session ID for the world.
    userRole = getCookieDetails('user_role');
	$('body').addClass('loggedin');
	$('html').removeClass('notloggedin');
	nliHolder = $('div#wrapper');
	$('div#wrapper').remove();
	$('div#interface_wrapper').show();
	CreateActivateTabs();
    if(userRole != 1)
    {
        $('.Admin_btn').hide();
    }
	activateLogOut();
}

//HOME SCREEN/////////////////////////////////////////////////////////////////////////////////
function copySurvey(surveyID){
	$('div.closealert').live('click', function(){
		$('div#yoursurveys').unblock();
	})
		$.getJSON(ReuseSurvey, { s: sessionID, sid: surveyID }, function(json){
			    if (json.error){
                	$('div#yoursurveys').unblock();
                    miniErrors('div#yoursurveys', json);
                } else {
					var theMessage = 'A copy of the survey has been created. Visit the builder to edit it or the distributor to send it out! <div class="linkstyling lighten closealert">Close this</div>';
					$('div#yoursurveys').block({message:theMessage});
                }
		})	
}

function drawRespondentGraph(respondentInfo){
						var startedNumber = Number(respondentInfo.startedSurvey);
						var completedNumber = Number(respondentInfo.completedSurvey);
						var notFinished = startedNumber - completedNumber;
						var completed = [[completedNumber, 0]];
						var notCompleted = [[notFinished, 0]];
						var maxNum = Number(respondentInfo.smsSent);
						var didntStart = maxNum-startedNumber;
						var tickArr = new Array();
						for (i=0;i<maxNum+1;i++){
							tickArr[i] = i;
						}
						plot2 = $.jqplot('respondent_ov_graph', [completed, notCompleted], {
						    stackSeries: true, 
						    legend: {show: false, location: 'sw'},
						    seriesDefaults: {
						        renderer: $.jqplot.BarRenderer, 
						        rendererOptions: {barDirection: 'horizontal', barWidth: 300, shadowOffset: 0, shadowDepth: 0, shadowAlpha: 0} //replace width with number of SMS sent
						    },
						    grid: {
        						drawGridLines: true    // wether to draw lines across the grid or not.
    						},

						    series: [
						        {label: 'Started'}, 
						        {label: 'Completed'}
						    ],
							axes: {
							        xaxis: {
							        show: false,    // wether or not to renderer the axis.  Determined automatically.
							        min: 0,      // minimum numerical value of the axis.  Determined automatically.
							        max: maxNum,      // maximum numverical value of the axis.  Determined automatically.
							        pad: 0,       // a factor multiplied by the data range on the axis to give the 
							                        // axis range so that data points don't fall on the edges of the axis.
							        ticks: tickArr,      // a 1D [val1, val2, ...], or 2D [[val, label], [val, label], ...] 
							                        // array of ticks to use.  Computed automatically.
							        numberTicks: undefined,
							        renderer: $.jqplot.LinearAxisRenderer,  // renderer to use to draw the axis,
							        rendererOptions: {},    // options to pass to the renderer.  LinearAxisRenderer +
							                                // has no options,
							        showTicks:true,        // wether or not to show the tick labels,
							        showTickMarks: true  // wether or not to show the tick marks
							        },
							        
							        yaxis: {
							        show: false,    // wether or not to renderer the axis.  Determined automatically.
							        min: null,      // minimum numerical value of the axis.  Determined automatically.
							        max: null,      // maximum numverical value of the axis.  Determined automatically.
							        pad: 0,       // a factor multiplied by the data range on the axis to give the 
							                        // axis range so that data points don't fall on the edges of the axis.
							        ticks: [],      // a 1D [val1, val2, ...], or 2D [[val, label], [val, label], ...] 
							                        // array of ticks to use.  Computed automatically.
							        numberTicks: undefined,
							        renderer: $.jqplot.LinearAxisRenderer,  // renderer to use to draw the axis,
							        rendererOptions: {},    // options to pass to the renderer.  LinearAxisRenderer 
							                                // has no options,
							        showTicks:false,        // wether or not to show the tick labels,
							        showTickMarks: false    // wether or not to show the tick marks
							        },
							        x2axis: {
							            // same options as axesDefaults
							        },
							        y2axis: {
							            // same options as axesDefaults
							        }
							    },
							    
            				grid: {
							        drawGridLines: true,    // wether to draw lines across the grid or not.
							        background: '#ccc',  // CSS color spec for background color of grid.
							        borderColor: '#fff', // CSS color spec for border around grid.
							        borderWidth: 0,       // pixel width of border around grid.
							        shadow: false,           // draw a shadow for grid.
							        renderer: $.jqplot.CanvasGridRenderer,  // renderer to use to draw the grid.
							        rendererOptions: {}     // options to pass to the renderer.  Note, there are no
							                                // other grid renderers available and CanvasGridRenderer
													    }
						});
					$('#report_left_col_wrapper').append('<table id="overviewlist"></table>');
                   	
						$('#overviewlist').append('<tr class="completed"><td>Completed:</td><td>'+completedNumber+'<td></tr>');
						if (notFinished != 0){
							$('#overviewlist').append('<tr class="notcompleted"><td>Not Complete:</td><td>'+notFinished+'<td></tr>');
						}
						$('#overviewlist').append('<tr class="didntstart"><td>Didn\'t Start:</td><td>'+didntStart+'<td></tr>');
}

function drawIndividualQuestions(surveyID, qnNum, indiQn){
	var lineVals = [];
	var answerVals = [];
	var tickArr = [];
	var maxNum = 0;
	var seriesColorArray = ["#00667f","#ff5100"];
	$('#report_right_col').append('<div class="questionBoxes" id="qnNum_'+qnNum+'"><h3>'+indiQn.question+'</h3><div class="chartbox" id="chart_'+qnNum+'"></div></div>');
	$('#chart_'+qnNum).css('width','100%');
	$.each(indiQn.answers, function(i, eachAnswer){
		lineVals[i] = [eachAnswer.count, i+1];
		answerVals[i] = eachAnswer.answer;
		if (maxNum < parseInt(eachAnswer.count)){
			maxNum = parseInt(eachAnswer.count)+2;
			}
	})
			for (i=0;i<maxNum;i++){
				tickArr[i] = i;
			}
			
			var lineV = lineVals;
			var plot3 = $.jqplot('chart_'+qnNum, [lineV], {
				seriesColors: seriesColorArray,
			    legend:{show:false},
			    seriesDefaults:{
			    	lineWidth: 0.5,
			        renderer:$.jqplot.BarRenderer, 
			        rendererOptions:{barDirection:'horizontal', barPadding: 1, barMargin:1, barWidth: 25 }, 
			        shadow:false
		        },
		        
			    axes:{
			        xaxis:{
			        	min:0,
			        	max: maxNum,
			        	ticks: tickArr
		        	}, 
			        yaxis:{
			            renderer:$.jqplot.CategoryAxisRenderer, 
			            ticks: answerVals
			        }
			    },
			    grid: {
							        drawGridLines: true,    // wether to draw lines across the grid or not.
							        background: '#fff',  // CSS color spec for background color of grid.
							        borderColor: '#fff', // CSS color spec for border around grid.
							        borderWidth: 0,       // pixel width of border around grid.
							        shadow: false,           // draw a shadow for grid.
							        renderer: $.jqplot.CanvasGridRenderer,  // renderer to use to draw the grid.
							        rendererOptions: {}     // options to pass to the renderer.  Note, there are no
							                                // other grid renderers available and CanvasGridRenderer
  					  }
			});	
}


function showResults(surveyID,surveyTitle,surveyDate,surveyTime){
    $('#surveylist').hide();
    $('#accountSummary').hide();
    $('#exportCsv').show();
    $('#exportCsv').data('sid', surveyID);
    $('#Home h2.page_title').empty().append('<span class="backtohome linkstyling">Home</span> > '+surveyTitle);
    $('#yoursurveys .screentitle').empty().append(surveyTitle);
    //$('#yoursurveys .screentitle').empty().append('<span class="backtohome linkstyling">Your Deployed Surveys</span> > '+surveyTitle);
    $('span.backtohome').click(function(){
        $('#Home h2.page_title').empty().append('Home');
        $('div#reporting').remove();
        $('#surveylist').show();
        $('#accountSummary').show();
        $('#exportCsv').hide();
        $('#yoursurveys .screentitle').empty().append('Your Deployed Surveys');
        $('#yoursurveys').css("width", "700px");
    });
    $('#yoursurveys').css("width", "940px");
    $('#yoursurveys').append('<div id="reporting"><div id="report_left_col"></div><div id="report_right_col"></div><div class="clearer"></div></div>');   
    //Get Survey Report 
    getSurveyReportData(surveyID);
    //Export Csv
    $('#exportCsv').click(function(){
        var surveyId = $('#exportCsv').data("sid");
        window.frames['exportCsvFrame'].location = ExportCsv+'&s='+sessionID+'&sid='+surveyId;
    });
    $('#deployedSurveys').click(function(){
        $('span.backtohome').click();
    });
}
function exportToCSV()
{
    var surveyId = $('#exportCsv').data("sid");
    window.frames['exportCsvFrame'].location = ExportCsv+'&s='+sessionID+'&sid='+surveyId;
}

function getSurveyReportData(surveyId)
{
    var api = new jGCharts.Api();

    $.getJSON(GetSurveyResponses, { s: sessionID, sid: surveyId }, function(json){
        if (json.error){
            $('div#yoursurveys').unblock();
        } else {
            var smsSent = json.GetSurveyResponses.overview.smsSent;
            var startedSurvey = json.GetSurveyResponses.overview.startedSurvey;
            var completedSurvey = json.GetSurveyResponses.overview.completedSurvey;
            var api = new jGCharts.Api();
            var opt = {
                data : [[completedSurvey, startedSurvey, smsSent]],
                type : 'bhg',
                legend : ['Completed', 'Started', 'Surveys Sent(by SMS)'],
                grid: true
            };
            jQuery('<img>').attr('src', api.make(opt)).appendTo('#report_left_col');

            var surveyResponses = json.GetSurveyResponses.responses;
            $.each(surveyResponses, function(i, survey){
                var apir = new jGCharts.Api();
                var surveyQues = survey.question;
                var surveyAns = survey.answers;
                var ansArr = Array();
                var ansOptions = Array();
                var k = 0;
                $.each(surveyAns, function(j, ans)
                {
                    ansOptions[k] = ans.answer;
                    ansArr[k] = parseInt(ans.count);
                    k++;
                });
                var ansOpt = {
                    grid: true,
                    data : [ansArr],
                    type : 'bhg',
                    legend : ansOptions,
                    size: '500x220',
                    colors: ['47C6F2', 'EB3743', '7F4440', '602D91', 'F9A01B', '25B34B', 'Ed1C24', 'B2D235', 'F15A22', 'EC998C']
                };
                $('#report_right_col').append('<div id="surevyQues">'+surveyQues+'</div>');
                jQuery('<img>').attr('src', apir.make(ansOpt)).appendTo('#report_right_col');
            });
        }
    });    
}
function homeLoad(){
    if(purchaseToken)
    {
        $('#tabs').tabs('select', 4);
        return false;
    }

    $('#buildsurvey').click(function(){
        $('#yoursurveys').addClass('height');
        setBuildSurvey('yoursurveys');
    });	
    $('#buyMoreCredits').click(function() {
        $('#tabs').tabs( 'select' , 4);
    });
    $('#exportCsv').click(function(){
        exportToCSV();
    }); 
    $('#exportCsv').hide();
    setUserCreditsLeft('creditsLeft');
	$('#yourPublishedSurveys').hide();
    $('#yourPublicSurveys').hide();
	$.getJSON(GetDistributedSurveys, { s: sessionID }, function(json){
		if (json.error){
            miniErrors('div#yoursurveys', json);
            return false;
		}
		$('#yoursurveys').unblock();
        var activeSurveys = json.GetDistributedSurveys.surveys;
        if(activeSurveys)
        {
            var depSurveys = 0;
            $('table#surveylist').append('<tr><th>Id</th><th>Title</th><th>Responses</th><th>Deployed</th><th></th><th>&nbsp;</th></tr>');
            $.each(activeSurveys, function(i, currentsurvey){ // For each survey...
                if(currentsurvey.deployed_date)
                {
                    depSurveys = depSurveys+1;
                    var surveyDateArray = [];
                    var surveyTimeArray = [];
                    var surveyID = currentsurvey.id;
                    var surveyRef = currentsurvey.reference;
                    var surveyName = currentsurvey.title;
                    var surveyResponses = currentsurvey.responses;
                    var surveyCreated = currentsurvey.deployed_date;
                    surveyDateArray = surveyCreated.split(' ');
                    var surveyCreatedDate = surveyDateArray[0];
                    var surveyCreatedTime = surveyDateArray[1];
                    var surveyTimeArray = surveyCreatedTime.split('.');
                    var surveyCreatedTimeSplit = surveyTimeArray[0];
                    var titleShort = surveyName;
                    if(surveyName.length > 43)
                    {
                        titleShort = surveyName.substr(0, 43)+'...';
                    }                        
                        currentListing = '<tr id="surveyRow_'+surveyID+'"><td>'+surveyRef+'</td>';
                        currentListing += '<td><span class="linkstyling review_survey">'+titleShort+'</span></td>';
                        currentListing += '<td>'+surveyResponses+'</td><td>'+surveyCreated+'</td>';
                        currentListing += '<td><span class="linkstyling copy_survey">Create Copy</span></td>';
                        currentListing += '<td><span class="linkstyling delete_survey">Delete</span></td></tr>';
                    $('table#surveylist').append(currentListing);
    
                    $('tr#surveyRow_'+surveyID).data('sid',surveyID);
                    $('tr#surveyRow_'+surveyID).data('surveyName',surveyName);
                    $('tr#surveyRow_'+surveyID).data('surveyDeployedDate',surveyCreatedDate);
                    $('tr#surveyRow_'+surveyID).data('surveyDeployedTime',surveyCreatedTimeSplit);
    
                    $('tr#surveyRow_'+surveyID+' span.review_survey').click(function(){
                        var targetSurvey = $(this).parent().parent().data('sid');
                        var targetSurveyName = $(this).parent().parent().data('surveyName');
                        var targetSurveyDate = $(this).parent().parent().data('surveyDeployedDate');
                        var targetSurveyTime = $(this).parent().parent().data('surveyDeployedTime');
                        
                        showResults(targetSurvey,targetSurveyName,targetSurveyDate,targetSurveyTime);
                    });	
    
                    $('tr#surveyRow_'+surveyID+' .copy_survey').click(function(){
                        var targetSurvey = $(this).parent().parent().data('sid');
                        copySurvey(targetSurvey);
                    });
                            
                    $('tr#surveyRow_'+surveyID+' .delete_survey').click(function(){
                        var targetSurvey = $(this).parent().parent().data('sid');
                        var targetSurveyName = $(this).parent().parent().data('surveyName');
                        var theMessage = '<h3 class="confirmdeletetitle">'+targetSurveyName+'</h3>';
                            theMessage += 'Are you sure you want to delete this survey?<p class="confirmdialogueoptions">';
                            theMessage += '<span id="delete_'+targetSurvey+'" class="linkstyling lighten confirm_delete" title="'+targetSurvey+'">yes</span> ';
                            theMessage += '<span id="cancel_'+targetSurvey+'" class="linkstyling lighten cancel_delete">no</span></p>';
                        $('div#yoursurveys').block({css: {color: '#f42c52'},message:theMessage});
                        
                        $('span#cancel_'+targetSurvey).live('click', function(){
                            $('div#yoursurveys').unblock();
                        })
                
                        $('span#delete_'+targetSurvey).live('click', function(){
                            var surveyID = $(this).attr('title');
                            deleteSurvey(surveyID);
                            return false;
                        });
                    });				 	
                }
            });
            if(depSurveys == 0)
            {
                $('table#surveylist').append('<tr><td colspan="5" class="error">No deployed Surveys</td></tr>');
            }
        }
        else
        {
            $('table#surveylist').append('<tr><td colspan="5" class="error">No deployed Surveys</td></tr>');
        }
	});

    $('#viewMore').click(function(){
        $('#tabs').tabs( 'select' , 5);
    });
    $('#homeBuyCredits').click(function(){
        $('#tabs').tabs( 'select' , 4);
    });
    setUserCreditsLeft('homeCredits');
    $('#publishedSurveys').click(function(){
        $('#reportsMenu a').removeClass('subSlect');
        $('#publishedSurveys').addClass('subSlect');
        $('#yoursurveys').hide();
        $('#yourPublicSurveys').hide();
        $('#yourPublishedSurveys').show();
    });
    $('#deployedSurveys').click(function(){
        $('#yoursurveys').show();
        $('#yourPublishedSurveys').hide();
        $('#yourPublicSurveys').hide();
        $('#reportsMenu a').removeClass('subSlect');
        $('#deployedSurveys').addClass('subSlect');
    });
    $('#publicSurveys').click(function(){
        $('#yoursurveys').hide();
        $('#yourPublishedSurveys').hide();
        $('#yourPublicSurveys').show();
        $('#reportsMenu a').removeClass('subSlect');
        $('#publicSurveys').addClass('subSlect');
    });
    loadPublishedSurveys();
    loadPublicSurveys();
    $('#deployedSurveys').addClass('subSlect');
}
function loadPublishedSurveys()
{
    $.getJSON(GetPublishedSurveys, { s: sessionID}, function(json){
        var surveys = json.GetPublishedSurveys.surveys;
        if(surveys.length > 0)
        {
            $('#publishedlist').append('<tr><th>Id</th><th>Title</th><th>&nbsp;</th></tr>');
            $.each(surveys, function(i, survey) {
                var htm = '<tr id="'+survey.id+'"><td>'+survey.reference+'</td>';
                    htm += '<td>'+survey.title+'</td>';
                    htm += '<td><a class="unpublishSurvey">Unpublish</a></td>';
                    htm += '<td><a class="makeItPublic">Make Public</a></td>';
                    htm += '<td><a class="distSurvey">Distribute</a></td></tr>';
                $('#publishedlist').append(htm);
            });

            $('.unpublishSurvey').click(function(){
                unpublishSurvey(this);
            });
            $('.makeItPublic').click(function(){
                $('#yourPublishedSurveys').addClass('heightbig');
                var sid = $(this).parent().parent().attr("id");
                getPublicURL(sid, 'yourPublishedSurveys', '50');
                //makeItPublic(this);
            });
            $('.distSurvey').click(function(){
                $('#tabs').tabs( 'select' , 2);
            });
        }
        else
        {
            $('#publishedlist').append('<tr><td class="error" colspan="3">No Published Surveys</td></tr>');
        }
    }); 
}
function loadPublicSurveys()
{
    $.getJSON(GetPublicSurveys, { s: sessionID}, function(json){
        var surveys = json.GetPublicSurveys.surveys;
        if(surveys.length > 0)
        {
            $('#publiclist').append('<tr><th>Id</th><th>Title</th><th>Public Url</th><th>Days left</th></tr>');
            $.each(surveys, function(i, survey) {
                var htm = '<tr id="'+survey.id+'"><td>'+survey.reference+'</td>';
                    htm += '<td>'+survey.title+'</td>';
                    htm += '<td>'+survey.url+'</td>';
                    htm += '<td>'+survey.dayleft+'</td></tr>';
                $('#publiclist').append(htm);
            });
        }
        else
        {
            $('#publiclist').append('<tr><td class="error" colspan="3">No Public Surveys</td></tr>');
        }
    });
}
function unpublishSurvey(obj) 
{
    var sid = $(obj).parent().parent().attr("id");
    var msg = 'This action will unpublish your survey and you will be able to edit this survey under Builder tab.';
        msg += 'Click ok to proceed or cancel to cancel it';
        msg += '<p class="confirmdialogueoptions"><span class="confirmUnpublish">ok</span> <span class="cancelUnpublish">cancel</span></p>';
    $('#yourPublishedSurveys').block({css: {color: '#25C058', width: '25%'},message:msg});
    $('.confirmUnpublish').click(function() {
        $.getJSON(UpdateSurveyAttribute, { s: sessionID, sid: sid, name: 'published', value: 'false'}, function(res){
            if(res.error)
            {
                $('#yourPublishedSurveys').unblock();
                miniErrors('#yourPublishedSurveys', 'Failed to unpublish your survey');
                return false;
            }
            $('#'+sid).remove();
            $('#yourPublishedSurveys').unblock();
        });
    });
    $('.cancelUnpublish').click(function(){
        $('#yourPublishedSurveys').unblock();
    });
}
function makeItPublic(obj)
{
    var sid = $(obj).parent().parent().attr("id");
    $.getJSON(UpdateSurveyAttribute, {s: sessionID, sid: sid, name: 'public', value: 'true'}, function(res){
        if(res.error)
        {
            miniErrors('#yourPublicSurveys', res.error);
            return false;
        }
        //Else
    });
}
function getPublishedSurveys() {
    var userSurveys = Array();
    $.getJSON(GetPublishedSurveys, { s: sessionID}, function(json){
        userSurveys = json.GetPublishedSurveys.surveys;
    });

    return userSurveys;
}
function uploadLogo(){
	var currentSurvey = $('div#thebuilder').data('currentSurvey');
	new AjaxUpload('#upload_button', {
	  // Location of the server-side upload script
	  // NOTE: You are not allowed to upload files to another domain
	  action: UploadLogo,
	  // File upload name
	  name: 'picfile',
	  // Additional data to send
	  data: {
	    s: sessionID,
	    sid: currentSurvey
	  },
	  // Submit file after selection
	  autoSubmit: true,
	  // The type of data that you're expecting back from the server.
	  // HTML (text) and XML are detected automatically.
	  // Useful when you are using JSON data as a response, set to "json" in that case.
	  // Also set server response type to text/html, otherwise it will not work in IE6
	  responseType: false,
	  // Fired after the file is selected
	  // Useful when autoSubmit is disabled
	  // You can return false to cancel upload
	  // @param file basename of uploaded file
	  // @param extension of that file
	  onChange: function(file, extension){},
	  // Fired before the file is uploaded
	  // You can return false to cancel upload
	  // @param file basename of uploaded file
	  // @param extension of that file
	  onSubmit: function(file, extension) {
                if (! (extension && /^(gif)$/.test(extension))){
                        // extension is not allowed
                        var errorMSG = 'Sorry, logo files must be in GIF format';
                        miniErrors('div#thebuilder', errorMSG);
                        // cancel upload
                        return false;
                }

	  },
	  // Fired when file upload is completed
	  // WARNING! DO NOT USE "FALSE" STRING AS A RESPONSE!
	  // @param file basename of uploaded file
	  // @param response server response
	  onComplete: function(textStatus,data) {
        data = data.replace('<pre>', '').replace('</pre>', '');
        var inJSON = jQuery.toJSON(data);
        if (inJSON.UploadLogo.success=='true'){
			$.getJSON(GetSurveyDetails, { s: sessionID, sid: currentSurvey}, function(json){
					    if (json.error){
		                    miniErrors('div#thebuilder', json);
		                } else {
		                	$('div#thebuilder').data('surveyLogo', json.GetSurveyDetails.survey.logo)
        					loadLogo();
		                }
			});	        
        }
	  }
	});
}

function colorPickerInits(){
	$('#theme_table tr').each(function(i){
		var currentRow = '#'+$(this).attr('id');
		var currentRowClass = '.'+$(this).attr('id');
		var currentColor = '#'+hexColors($(currentRow + ' div.colorbox').css('background-color'));
        
		var currentCol;

		$(currentRow + ' div.colorbox').ColorPicker({
			color: currentColor,
			onShow: function (colpkr) {
				$(colpkr).fadeIn(100);                
				return false;
			},
			onHide: function (colpkr) {
				$(colpkr).fadeOut(100);
				setSurveyThemes();
				return false;
			},
			onChange: function (hsb, hex, rgb) {
				currentCol = $('.colorpicker_hex input').val();
				$(currentRow + ' div.colorbox').css('background-color', '#' + hex);
				if (currentRowClass == '.page_text_row' || currentRowClass == '.title_text_row' || currentRowClass == '.current_questions_row' || currentRowClass == '.page_links_row' || currentRowClass == '.question_field_row' || currentRowClass == '.answer_text_row'){
					$(currentRowClass).css('color', '#' + hex);
				} else {
					$(currentRowClass).css('background-color', '#' + hex);
				}
			}
		});
	});
}

function deleteQuestion(qid){
	var sid = $('div#thebuilder').data('currentSurvey');
	var newPosition = $('#question_list li').index($('#question_'+qid));
	var oldPos = -1;
	$.getJSON(DeleteSurveyQuestion, { s:sessionID, sid:sid, question_id:qid}, function(json){
		if (json.error){
            miniErrors('div#thebuilder', json);
        } else {
            //sortQuestions(oldPos,newPosition,'1');
            var quesArr = json.DeleteSurveyQuestion.questions;
            if(quesArr.length > 0)
            {
                $.each(quesArr, function(i, question){
                    var qid = question.id;
                    var pos = question.position;
                    $('#question_'+qid).data('position',pos);
                });
            } 

            if ($('#survey_wrap').data('currentQuestion') == qid){
                var newQn = $('#question_'+qid).next().data('qid');
                if(newQn == undefined){
                	newQn = $('#question_'+qid).prev().data('qid');
                }
                if (newQn == undefined){
					$('.currentQuestion').removeClass('currentQuestion');
					$('div#start_message').addClass('currentQuestion');
					
					if (!$('#addanswer').hasClass('inactive')){
							$('#addanswer').addClass('inactive');
					}
					$('div#survey_contents').hide("slide", {direction: "up"}, 100, function(){
						$('div#survey_contents').show("slide", {direction: "up"}, 200);
						$('div.surv_content').each(function(){
							if($(this).attr('id')!='survey_start_message'){
								$(this).hide();
							} else {
								$(this).show()
								
							}
						})
					});                			
                }
                if (qid){
						$('#answer_list').empty();
						$('div.surv_content').each(function(){
								$('#survey_wrap').data('currentQuestion', newQn);
								$('#survey_wrap .question').text($('#question_'+ newQn).data('question'));
								$('#survey_wrap #survey_pagedescription').text($('#question_'+ newQn).data('description'));
								
						})
						retrieveAnswers(newQn);
					} else {
					if (!$('#addanswer').hasClass('inactive')){
								$('#addanswer').addClass('inactive');
						}
						$('div.surv_content').each(function(){
							if($(this).attr('id')!='survey_start_message'){
								$(this).hide();
							} else {
								$(this).show()
								
							}
						})								
					}
            }                	
            $('#question_'+qid).remove();
            if ($('#question_list li').length < 9){
                $('#question_list').css('height','auto').css('overflow','visible').css('padding-bottom','0');
            }
            $('#thebuilder').unblock();
        }
	});	
}

function deleteAnswer(aid){
	var sid = $('div#thebuilder').data('currentSurvey');
	var newPosition = $('#answer_list li').index($('#answer_'+aid));
    var questionId = $('div#survey_wrap').data('currentQuestion');
	var oldPos = -1;
	$.getJSON(DeleteAnswer, { s:sessionID, sid:sid, answer:aid, question_id: questionId}, function(json){
		if (json.error){
            miniErrors('div#survey_wrap', json);
        } else {
            retrieveAnswers(questionId);
            //sortAnswers(oldPos,newPosition,'1');           	
            $('li#answer_'+aid).remove();
            $('div#survey_wrap').unblock();
        }
	});	
}

function confirmdeleteQuestion(qid, question){
		var theMessage = '<h3 class="confirmdeletetitle">'+question+'</h3><p>Are you sure you want to delete this question?</p> <p class="confirmdialogueoptions"><span class="linkstyling lighten confirm_delete_qn">yes</span> <span class="linkstyling lighten cancel_delete_qn">no</span></p>'
		$('#thebuilder').block({css: {color: '#f42c52'},message:theMessage});
		$('.confirm_delete_qn').click(function(){
			deleteQuestion(qid);
		})	
		$('.cancel_delete_qn').click(function(){
			$('#thebuilder').unblock();
		})				
}

function confirmdeleteAnswer(aid, answer){
		var theMessage = 'Are you sure you want to delete the answer "'+answer+'"? <p><span class="linkstyling lighten confirm_delete_ans">yes</span> <span class="linkstyling lighten cancel_delete_ans">no</span></p>'
		$('#survey_wrap').block({css: {color: '#f42c52', width: '75%'},message:theMessage});
		$('.confirm_delete_ans').click(function(){
			deleteAnswer(aid);
		})	
		$('.cancel_delete_ans').click(function(){
			$('#survey_wrap').unblock();
		})				
}

function displayQn(question_id, question, description, position, show){
    var htm = '<li id="question_'+question_id+'">';
        htm += '<div class="q_list_wrapper">';
        htm += '<div class="survey_question linkstyling">'+question+'</div>';
        htm += '<div class="delete_question_box"><span class="delete_question">delete this question</span></div>';
        htm += '</div></li>';
        $('#question_list').append(htm);
        if(position > 9){
            $('#question_list').css('height','320px').css('overflow','scroll').css('overflow-x', 'hidden').css('-ms-overflow-x', 'hidden').css('padding-bottom','13px');
        }
        $('#question_'+question_id).data('qid',question_id);
        $('#question_'+question_id).data('question',question);
        $('#question_'+question_id).data('description',description);
        $('#question_'+question_id).data('position',position);

		$('#question_'+question_id+' .q_list_wrapper').mousedown(function(){
			return false;
		});
		$('#question_'+question_id+' .q_list_wrapper').mouseenter(function(){
			$('#question_'+question_id+' .delete_question_box').show();
		});
		
		$('#question_'+question_id+' .q_list_wrapper').mouseleave(function(){
			$('#question_'+question_id+' .delete_question_box').hide();
		});

		$('#question_'+question_id+' .delete_question').click(function(){
			confirmdeleteQuestion(question_id, $('#question_'+question_id).data('question'));
		});							
                	
		$('#question_'+question_id+' .survey_question').click(function(){
			$('#survey_wrap').block();
			$('.currentQuestion').removeClass('currentQuestion');
			$('#question_'+question_id).addClass('currentQuestion');
			if ($('#addanswer').hasClass('inactive')){
				$('#addanswer').removeClass('inactive');	
			}
			$('div#survey_contents').hide("slide", {direction: "up"}, 200, function(){
				$('#answer_list').empty();
				$('div.surv_content').each(function(){
					if($(this).attr('id')!='survey_pagecontent'){
						$(this).hide();
					} else {
						$(this).show();
						$('#survey_wrap').data('currentQuestion',question_id);
						$('#survey_wrap .question').html($('#question_'+question_id).data('question').replace(/(\r\n|\r|\n)/g, "<br />"));
                        var desc = $('#question_'+question_id).data('description');
                        if(desc)
                        {
                            desc = desc.replace(/(\r\n|\r|\n)/g, "<br />");
                        }
                        else
                        {
                            desc = 'Describe your needs.';
                        }
                        $('#survey_wrap #survey_pagedescription').html(desc);
						retrieveAnswers(question_id);
					}
				});
				$('div#survey_contents').show("slide", {direction: "up"}, 200);
			});
		});
        if(show)
        {
            $('#question_'+question_id+' .survey_question').click();
        }
}

function displayAns(answer_id, answer, position){
    $('#answer_list').append('<li id="answer_'+answer_id+'" class="answer"><div class="answer_text_row">'+answer+'</div><div class="delete_answer_box"><span class="delete_answer">delete this answer</span></div></li>');
    $('#answer_'+answer_id).data('aid',answer_id);
    $('#answer_'+answer_id).data('answer',answer);
    $('#answer_'+answer_id).data('position',position);
    $('#answer_'+answer_id+' .answer_text_row').css('color',$('tr#answer_text_row .colorbox').css('background-color'));
    $('#answer_'+answer_id+' .answer_text_row').editable(
    function(value, settings) {
        value = value.replace(/<\/?[^>]+(>|$)/g, "");
        updateAnswer($('#answer_'+answer_id).data('aid'),value,$('#answer_'+answer_id).data('position'));
    return(value);
    },{ 
      height: '14px',
      width: '137px',					  	
      select : true,
      submit : 'OK',
      cancel : 'cancel',
      cssclass : 'editable',
      onblur : 'mouseout'
    });
    $('#answer_'+answer_id).mouseenter(function(){
	    $('#answer_'+answer_id+' .delete_answer_box').show();
    });

    $('#answer_'+answer_id).mouseleave(function(){
	    $('#answer_'+answer_id+' .delete_answer_box').hide();
    });

    $('#answer_'+answer_id+' .delete_answer').click(function(){
	    confirmdeleteAnswer(answer_id, $('#answer_'+answer_id).data('answer'));
    });
    $('#answer_list li').draggable({
            //connectToSortable: '#tempAnswerList',
            helper: 'clone',
            revert: 'invalid',
            snap: true,
            stop: function(event, ui){
                //alert('as');
            }
        });								  
}

function addAns(){
    var htm = '<label class="">Answer: </label>';
        htm += '<input type="text" id="question_answer" />';
        htm += '<p><input type="button" class="standard_btn small_button" id="addNextAnswer" value="Save & add another" />';
        htm += '<span class="linkstyling lighten marginleft" id="cancelQuestionAnswer">Done</span></p>';

    $('div#thebuilder').block({
        overlayCSS: {
            backgroundColor: '#292929',
            opacity: '0.5'
        },
        css: {
            color: '#000',
            backgroundColor: '#fff',
            textAlign: 'left',
            left: '10px',
            top: '20%'
        },
        message:htm
    }); 
    $('.blockElement').css('top', '100px');

    $('#question_answer').focus();

    $('#addQuestionAnswer').click(function(){
        var answer = $('#question_answer').val();
        saveAnswer(answer);
        $('div#thebuilder').unblock();
    });
    $('#cancelQuestionAnswer').click(function(){
        var answer = $('#question_answer').val();
        if(answer)
        {
            saveAnswer(answer);
        }
        $('div#thebuilder').unblock();
    });
    $('#addNextAnswer').click(function(){
        var answer = $('#question_answer').val();
        if(answer)
        {
            saveAnswer(answer);
        }
        $('#question_answer').val('');
    });
    /*
	$('#addanswer').addClass('inactive');
	$('#addanswer').val('Adding Answer...');
	var surveyID = $('div#thebuilder').data('currentSurvey');
	var questionID = $('div#survey_wrap').data('currentQuestion');
	var answer = 'Replace this text.';
	var position = $('#answer_list li').length + 1;
	$.getJSON(AddAnswer, { s:sessionID, sid:surveyID, question_id:questionID, answer:answer, position: position}, function(json){
			    if (json.error){
                    miniErrors('div#thebuilder', json);
                } else {
                	$('p#question_no_answers').hide();
                	$('#addanswer').removeClass('inactive');                	
                	$('#addanswer').val('Add Answer');
                	var answer_id = json.AddAnswer.id;
                	displayAns(answer_id, answer, position);
                }
	});	
    */
}
function saveAnswer(answer)
{
    var surveyID = $('div#thebuilder').data('currentSurvey');
    var questionID = $('div#survey_wrap').data('currentQuestion');
    var position = $('#answer_list li').length + 1;
    $.getJSON(AddAnswer, { s:sessionID, sid:surveyID, question_id:questionID, answer:answer, position: position}, function(json){
        if (json.error)
        {
            $('div#thebuilder').unblock();
            miniErrors('div#thebuilder', json.error);
        }
        else
        {
            $('p#question_no_answers').hide();
            var answer_id = json.AddAnswer.id;
            displayAns(answer_id, answer, position);
        }
    });
}
function AddSurveyQn(){
     var htm = '<label class="">Question: </label>';
        htm += '<input type="text" id="survey_question" />';
        htm += '<p class=""><input type="button" class="small_button standard_btn" id="addSurveyQuestion" value="Add" />';
        htm += '<span class="linkstyling lighten marginleft" id="cancelSurveyQuestion">Cancel</span></p>';
    $('div#thebuilder').block({
        overlayCSS: {
            backgroundColor: '#292929',
            opacity: 0.5
        },
        css: {
            color: '#000',
            backgroundColor: '#fff',
            textAlign: 'left',
            left: '10px'
        }, 
        message:htm
    });
    
    $('#survey_question').focus();

    $('#addSurveyQuestion').click(function(){
        var question = $('#survey_question').val();
        var surveyID = $('div#thebuilder').data('currentSurvey');
        var position = $('#question_list li').length + 1;
        $.getJSON(AddSurveyQuestion, { s: sessionID, sid: surveyID, question:question, description:'', position:position}, function(json){
            if (json.error)
            {
                $('div#thebuilder').unblock();
                miniErrors('div#thebuilder', json);
            }
            else
            {
                $('div#thebuilder').unblock();
                var description = 'Click here to edit question description.';
                var question_id = json.AddSurveyQuestion.id;
                displayQn(question_id, question, description, position, true);
            }
        });
    });
    $('#cancelSurveyQuestion').click(function(){
        $('div#thebuilder').unblock();
    }); 
}


function editableBits(){
    $(".editable_title").editable(
  	    function(value, settings) { 
            value = value.replace(/<\/?[^>]+(>|$)/g, "");
            updateSurvey(value,$('.editable_desc').html(),$('.editable_end').html(), 'editable_title');        	
    	    return value.replace(/(\r\n|\r|\n)/g, "<br />");
    },{ 
  	  height: '20px',
  	  width: '210px',
  	  select : true,
      submit : 'OK',
      cancel : 'cancel',
      cssclass : 'editable',
      onblur : 'mouseout',
      type: 'textarea',
      data: function(value, settings) {      
        var retval = value.replace(/<br[\s\/]?>/gi, '\n');
        return retval;
      }
    });
    
  $(".editable_desc").editable(
  	function(value, settings) { 
        value = value.replace(/<\/?[^>]+(>|$)/g, "");
    	updateSurvey($('.editable_title').html(),value,$('.editable_end').html(), 'editable_desc');
	    return value.replace(/(\r\n|\r|\n)/g, "<br />");
  },{ 
  	  height: '100px',
  	  width: '185px',      
  	  select : true,
      submit : 'OK',
      cancel : 'cancel',
      cssclass : 'editable',
      onblur : 'mouseout',
      type: 'textarea', 
      data: function(value, settings) {      
        var retval = value.replace(/<br[\s\/]?>/gi, '\n');
        return retval;
      }
  });
  $(".editable_end").editable(
  	function(value, settings) { 
        value = value.replace(/<\/?[^>]+(>|$)/g, "");
    	updateSurvey($('.editable_title').html(),$('.editable_desc').html(),value, 'editable_end');
	    return value.replace(/(\r\n|\r|\n)/g, "<br />");
  },{ 
  	  height: '100px',
  	  width: '195px',
  	  type   : 'textarea',
      select : true,
      submit : 'OK',
      cancel : 'cancel',
      cssclass : 'editable',
      onblur : 'mouseout',
      data: function(value, settings) {      
        var retval = value.replace(/<br[\s\/]?>/gi, '\n');
        return retval;
      }
  });

  $(".editable_question").editable(
  	function(value, settings) { 
        value = value.replace(/<\/?[^>]+(>|$)/g, "");
  	    var position = $('#question_'+$('div#survey_wrap').data('currentQuestion')).data('position');
      	$('#question_'+ $('div#survey_wrap').data('currentQuestion')).data('description',$('#survey_pagedescription').html());
        $('#question_'+ $('div#survey_wrap').data('currentQuestion')).data('question',value);  	
    	updateQuestion('', $('#survey_pagedescription').html(), value, position, 'editable_question');
	    return value.replace(/(\r\n|\r|\n)/g, "<br />");
  },{ 
  	  height: '57px',
  	  width: '196px',
  	  select: true,
      submit: 'OK',
      cancel: 'cancel',
      cssclass: 'editable',
      onblur: 'mouseout',
      type: 'textarea',
      data: function(value, settings) {      
        var retval = value.replace(/<br[\s\/]?>/gi, '\n');
        return retval;
      }
  });
  
  $(".editable_qn_descr").editable(
  	function(value, settings) {
        value = value.replace(/<\/?[^>]+(>|$)/g, "");
  	    var position = $('#question_'+$('div#survey_wrap').data('currentQuestion')).data('position');
      	$('#question_'+$('div#survey_wrap').data('currentQuestion')).data('description',value);
        $('#question_'+$('div#survey_wrap').data('currentQuestion')).data('question',$('#survey_pagecontent .question_field_row').html());
    	updateQuestion('', value, $('#survey_pagecontent .question_field_row').html(), position, 'editable_qn_descr');
	    return value.replace(/(\r\n|\r|\n)/g, "<br />");
  },{ 
  	  height: '50px',
  	  width: '194px',  
	  select: true,
      submit: 'OK',
      cancel: 'cancel',
      cssclass: 'editable',
      onblur: 'mouseout',
      type: 'textarea',
      data: function(value, settings) {      
        var retval = value.replace(/<br[\s\/]?>/gi, '\n');
        return retval;
      }
  }); 

    $('#startButtonEdit').editable(function(value, strings){
        var surveyID = $('div#thebuilder').data('currentSurvey');
        value = value.replace(/<\/?[^>]+(>|$)/g, "");
        $.getJSON(UpdateSurveyAttribute, { s: sessionID, sid: surveyID, name: 'start_button_text', value: value}, function(res){
            if(res.error)
            {

            }
        });
        return value;
    }, {
        height: '18px',
        width: '175px',
        select: true,
        submit: 'OK',
        cancel: 'cancel',
        cssclass: 'editable',
        onblur: 'mouseout',
        type: 'textarea',
        data: function(value, settings) {
            var retval = value.replace(/<br[\s\/]?>/gi, '\n');
            return retval;
        }
    });
}

function loadLogo(){
        var logoUrl = $('div#thebuilder').data('surveyLogo');
        if (logoUrl){
            $('div#survey_header img').attr("src", logoUrl+'?v='+Math.random());
        }
}

function setSurveyThemes(){
	var surveyID = $('div#thebuilder').data('currentSurvey');
	var logoBG = hexColors($('tr#logo_bg_row div.colorbox').css('background-color'));
	var titleBG = hexColors($('tr#title_bg_row div.colorbox').css('background-color'));
	var titleTXT = hexColors($('tr#title_text_row div.colorbox').css('background-color'));
	var pageBG = hexColors($('tr#page_bg_row div.colorbox').css('background-color'));
	var pageTXT = hexColors($('tr#page_text_row div.colorbox').css('background-color'));
	var pageLINKS = hexColors($('tr#page_links_row div.colorbox').css('background-color'));
	var currentQST = hexColors($('tr#current_questions_row div.colorbox').css('background-color'));
	var questionFIELD = hexColors($('tr#question_field_row div.colorbox').css('background-color'));
	var ansTXT = hexColors($('tr#answer_text_row div.colorbox').css('background-color'));
	$.getJSON(SetSurveyTheme, { s: sessionID, sid: surveyID, logoBg: logoBG, titleBg: titleBG, titleColor: titleTXT, pageBg: pageBG, linkColor: pageLINKS, currQuestion: currentQST,  quesColor:questionFIELD, ansText:ansTXT, textColor:pageTXT}, function(json){
			    if (json.error){
                    miniErrors('div#thebuilder', json);
                } else {
                	
                }
	});	
}

function colorBoxing(){
	$('tr#logo_bg_row div.colorbox').css('background-color', $('#survey_header').css('background-color'));
	$('tr#title_bg_row div.colorbox').css('background-color', $('#survey_surveytitle').css('background-color'));
	$('tr#title_text_row div.colorbox').css('background-color', $('#survey_surveytitle .title_text_row').css('color'));
	$('tr#page_bg_row div.colorbox').css('background-color', $('#survey_wrap').css('background-color'));
	$('tr#page_text_row div.colorbox').css('background-color', $('#survey_wrap').css('color'));
	$('tr#page_links_row div.colorbox').css('background-color', $('#survey_wrap a').css('color'));
	$('tr#current_questions_row div.colorbox').css('background-color', $('#survey_wrap .current').css('color'));
	$('tr#question_field_row div.colorbox').css('background-color', $('#survey_wrap .question').css('color'));
}

function initNewSurvey(){
	buildType = 'normal';
	$('#buildermenu').hide();
	$('#buildnewsurvey').hide();
	$('#thebuilder').show();
	var surveyTitle, surveyDesc, surveyEndMsg;
	surveyTitle = 'New Survey';
	surveyDesc = 'Click here to update your nature of the survey.';
	surveyEndMsg = 'Click here to update your thank message to survey users.';
	$.getJSON(CreateNewSurvey, { s: sessionID, title: surveyTitle, desc: surveyDesc, end_message: surveyEndMsg  }, function(json){
		if (json.error){
            $('div#thebuilder').unblock();
            miniErrors('div#thebuilder', json);
        } else {
		    $('div#thebuilder').unblock();
            var surveyId = json.CreateNewSurvey.id;
		    $('div#thebuilder').data('currentSurvey', surveyId);
            uploadLogo();		    
            setNewSurveyThemes(surveyId);
            $('#question_list').html('');  
            $('div#start_message').trigger('click');
            initEditSurvey(surveyId);
            //Mobile view overlay
            $('#survey_wrap').block({
                css: {
                    color: '#25C058', 
                    width: '80%'
                },
                message:'Use this mobile pane to update your survey details, questions and answers. Simply click on the sample texts and update your details. <div id="ol_continue">click here to continue</div>',
                timeout: 6000
            });
        }
	});
}
function setNewSurveyThemes(surveyId)
{
    $.getJSON(SetNewSurveyTheme, {s: sessionID, survey_id: surveyId}, function(res){
        //
    });
}
function displayQuestions(questionArray){
    $('#question_list').html('');  
    $.each(questionArray, function(i){
        var question_id = questionArray[i].id;
        var question = questionArray[i].question;
        var description = questionArray[i].description;
        var position = questionArray[i].position;
        displayQn(question_id, question, description, position, false);
    });
    
    $('#question_list').sortable({
        start: function(event, ui) {
        },
        stop: function(event,ui){
            var currPosition = $('#question_list li').index(ui.item);
            var prevPosition = ui.item.data('position');
            var quesId = ui.item.data('qid');
            sortQuestions(currPosition, prevPosition, quesId);
        }
    });
    $("#sortable").disableSelection();
}

function displayAnswers(answerArray){
	$('#answer_list').html('');
    answerArrayLength = answerArray.length+1;
	for (l=1;l<=answerArrayLength;l++){	
		$.each(answerArray, function(i){ // For each survey...
			if (answerArray[i].position == l){
	                	var answer_id = answerArray[i].id;
	                	var answer = answerArray[i].answer;
	                	var position = answerArray[i].position;
	                	displayAns(answer_id, answer, position);
	        }
		});
        //Answer drag and drop
        $('#answer_list li').draggable({
            //connectToSortable: '#tempAnswerList',
            helper: 'clone',
            revert: 'invalid',
            snap: true,
            stop: function(event, ui){
                //alert('as');
            }
        });    
	}
}

function retrieveAnswers(targetQuestion){
	$('p#question_no_answers').hide();
	var targetSurvey = $('div#thebuilder').data('currentSurvey');
    if(targetQuestion)
    { 
	    $.getJSON(GetAnswers, { s:sessionID, sid:targetSurvey, question_id:targetQuestion}, function(json){
			$('#survey_wrap').unblock();		
			if (json.error){
			    miniErrors('div#thebuilder', json);
            } else {
                if(json.GetAnswers.answers.length > 0)
                {   
                    displayAnswers(json.GetAnswers.answers);
                }
                else
                {
                    $('p#question_no_answers').show();
                }
            }
	    });		
    }
}

function retrieveQuestions(targetSurvey){
	$.getJSON(GetQuestions, { s:sessionID, sid:targetSurvey, full:'1'}, function(json){
			    if (json.error){
                    $('#question_list').empty();
			    	return false;                    
                } else {
					displayQuestions(json.GetQuestions.questions_full);
                }
	});		
}

function sortQuestions(currPosition, prevPosition, quesId, deleteState){
    var surveyId = $('div#thebuilder').data('currentSurvey'); 
    currPosition = currPosition+1;
    
    $.getJSON(UpdateQuestionPosition, {s:sessionID, curr_position: currPosition, prev_position: prevPosition, question_id: quesId, survey_id: surveyId}, function(response){
        if(response.error)
        {
            return false;
        }
        var quesArr = response.UpdateQuestionPosition.questions;
        if(quesArr.length > 0)
        {
            $.each(quesArr, function(i, question){
                var qid = question.id;
                var pos = question.position;
                $('#question_'+qid).data('position',pos);
            });
        }
    });
}

function sortAnswers(startPos,endPos,deleteState){
	if (startPos > endPos || deleteState == 1){ //item is moved up in the list. ie from 3rd to 1st
		$('#answer_list li').each(function(i){
			if (i>endPos) {
				var newPosition = $('#answer_list li').index($(this))+1;
				var targetAnswer = $(this).data('aid');
                var answer = $(this).data('answer');
                $(this).data('position',newPosition);
				updateAnswer(targetAnswer, answer, newPosition);
			}
			})
	}
	if (startPos == endPos){
		return false;
	}
	if (startPos < endPos){ //item is moved down in the list. ie from 1st to 3rd
		$('#answer_list li').each(function(i){
			if (i<endPos) {
				var newPosition = $('#answer_list li').index($(this))+1;
				var targetAnswer = $(this).data('aid');
                var answer = $(this).data('answer');
                $(this).data('position',newPosition);
				updateAnswer(targetAnswer, answer, newPosition);
			}
		})
	}
}

function assignColors(targetSurvey){
	$.getJSON(GetSurveyTheme, { s:sessionID, sid:targetSurvey}, function(json){
			    if (json.error){
                    miniErrors('div#thebuilder', json);
                    return false;
                } else {
                		var themeDet = json.GetSurveyTheme.themes;
						$('#survey_header').css('background-color','#'+themeDet.logoBg);
						$('#survey_surveytitle').css('background-color','#'+themeDet.titleBg);
						$('#survey_surveytitle .title_text_row').css('color','#'+themeDet.titleColor);
						$('#survey_wrap').css('background-color','#'+themeDet.pageBg);
						$('#survey_wrap').css('color','#'+themeDet.textColor);
						$('#survey_wrap a').css('color','#'+themeDet.linkColor);
						$('#survey_wrap .current').css('color','#'+themeDet.currQuestion);
						$('#survey_wrap .question').css('color','#'+themeDet.quesColor);
						$('#survey_wrap .answer').css('color','#'+themeDet.ansText);
						$('tr#answer_text_row div.colorbox').css('background-color', '#'+themeDet.ansText);//because answers are dynamically generated.
						loadLogo();
						colorBoxing();
                        colorPickerInits();
						//$('div#thebuilder').unblock();
						
                }
	});		
}

function updateSurvey(surveyTitle,surveyDescription, surveyEndMsg, editingField){
	var targetSurvey = $('div#thebuilder').data('currentSurvey');
	$.getJSON(UpdateSurvey, { s:sessionID, sid:targetSurvey, title:surveyTitle, description:surveyDescription, end_message:surveyEndMsg}, function(json){
			    if (json.error){
                    miniErrors('div#thebuilder', json);
                    $('.'+editingField).text($('.'+editingField).data(editingField));
                    if(editingField == 'editable_title')
                    {
                        $('h2#survey_title_text').html($('.'+editingField).data(editingField));
                    }
                } else {
                    $('h2#survey_title_text').html(surveyTitle);
                    $('#surveyTitleHead').html(' > '+ surveyTitle); 
                }
	});	
}

function updateQuestion(targetQuestion, questionDescription, questionText, questionPosition, editingField){
	var targetSurvey = $('div#thebuilder').data('currentSurvey');
	if (!targetQuestion){
		var targetQuestion = $('div#survey_wrap').data('currentQuestion');
	}
	$.getJSON(UpdateSurveyQuestion, { s:sessionID, sid:targetSurvey, question_id:targetQuestion, description:questionDescription, question:questionText, position:questionPosition}, function(json){
			    if (json.error){
                    miniErrors('div#thebuilder', json);
                    var oldQues = $('#question_'+targetQuestion+' .survey_question').html();
                    $('.'+editingField).text(oldQues);
                } else {              	
                	$('#question_'+targetQuestion+' .survey_question').html(questionText);
                	$('#question_'+targetQuestion).data('question',questionText);
                }
	});	
}

function updateAnswer(targetAnswer, answerText, position){
	var targetSurvey = $('div#thebuilder').data('currentSurvey');
	$.getJSON(UpdateAnswer, { s:sessionID, sid:targetSurvey, answer_id:targetAnswer, answer:answerText, position:position}, function(json){
			    if (json.error){
                    miniErrors('div#thebuilder', json);
                    var oldAns = $('#answer_'+targetAnswer).data('answer');
                    $('#answer_'+targetAnswer+' .answer_text_row').text(oldAns);
                } else {
                	$('#answer_'+targetAnswer).data('answer',answerText)
                }
	});	
}

function initEditSurvey(targetSurvey){
	buildType = 'normal';
	$('#buildermenu').hide();
	$('#buildnewsurvey').hide();    
	$('#thebuilder').show();  
	$('div#thebuilder').data('surveyLogo', null)
	$.getJSON(GetSurveyDetails, { s: sessionID, sid: targetSurvey}, function(json){
		if (json.error){
            miniErrors('div#thebuilder', json);
        } else {
            $('#surveyTitleHead').html(' > '+ json.GetSurveyDetails.survey.title);
            $('div#thebuilder').data('currentSurvey', targetSurvey);
            $('div#thebuilder').data('surveyLogo', json.GetSurveyDetails.survey.logo)
			uploadLogo();                	
		    $('h2#survey_title_text').html(json.GetSurveyDetails.survey.title);
            $('#startButtonEdit').html(json.GetSurveyDetails.survey.start_button_text);
		    $('#survey_surveytitle .title_text_row').html(json.GetSurveyDetails.survey.title.replace(/(\r\n|\r|\n)/g, "<br />"));
            $('.editable_title').data('editable_title', json.GetSurveyDetails.survey.title)//.replace(/(\r\n|\r|\n)/g, "<br />"));
		    $('#survey_start_message .editable_desc').html(json.GetSurveyDetails.survey.description.replace(/(\r\n|\r|\n)/g, "<br />"));
            $('.editable_desc').data('editable_desc', json.GetSurveyDetails.survey.description);//.replace(/(\r\n|\r|\n)/g, "<br />"));
		    $('#survey_end_message.editable_end').html(json.GetSurveyDetails.survey.end_message.replace(/(\r\n|\r|\n)/g, "<br />"));
            $('.editable_end').data('editable_end', json.GetSurveyDetails.survey.end_message);//.replace(/(\r\n|\r|\n)/g, "<br />"));
            $('#startButtonEdit').data('startButtonEdit', json.GetSurveyDetails.survey.start_button_text);
            if(json.GetSurveyDetails.survey.multiple_response_per_user)
            {
                $('#allowYes').attr('checked', 'true');
            }
            else
            {
                $('#allowNo').attr('checked', 'true');
            }
		    $('div#start_message').trigger('click');
            assignColors(targetSurvey);
		    retrieveQuestions(targetSurvey);   
            $('#surveyTestRun').click(function(){
                var surveyID = $('div#thebuilder').data('currentSurvey');
                sendTestRunSMS(surveyID, 'thebuilder');
            });
            $('#publishSurvey').click(function(){
                var surveyID = $('div#thebuilder').data('currentSurvey');
                publishSurvey(surveyID);
            });
            $("input[name='allow_multiple_response']").click(function(){
                var allow = $(this).val();
                var flag = 'false';
                if(allow == "yes")
                {
                    flag = 'true';
                }
                var surveyID = $('div#thebuilder').data('currentSurvey');
                $.getJSON(UpdateSurveyAttribute, { s: sessionID, sid: surveyID, name: 'multiple_response_per_user', value: flag}, function(res) {
                    if(res.error)
                    {
                        //error
                    }
                });
            });
        }
	});	
}
function sendTestRunSMS(sid, div)
{
    $.getJSON(GetUserData, { s: sessionID }, function(res){
        if(! res.error)
        {
            var msid = res.GetUserData.mobile;
            var msg = 'Your Mobile: <input type="text" id="testMobile" value="'+msid+'" />';
                msg+= '<p class=""><input type="button" class="confirmSend small_button standard_btn" value="Send" /> <span class="cancelSend">Cancel</span></p>';
            $('#'+div).block({
                overlayCSS: {
                    backgroundColor: '#292929',
                    opacity: 0.5
                },
                css: {
                    color: '#000', 
                    width: '30%',
                    backgroundColor: '#fff',
                    textAlign: 'left',
                    left: '10px'
                },
                message:msg
            });
            $('#testMobile').focus();
            $('.confirmSend').click(function(){
                var msid = $('#testMobile').val();
                $.getJSON(SendTestSurvey, {s: sessionID, msid: msid, sid: sid}, function(res){
                    if(!res.error)
                    {
                        setUserCreditsLeft('creditsLeft');
                        $('#'+div).unblock();
                        $('#'+div).removeClass('height');
                    }
                });
            });
            $('.cancelSend').click(function(){
                $('#'+div).removeClass('height');
                $('#'+div).unblock();
            });
        }
    });
}
function publishSurvey(sid)
{
    
    $.getJSON(UpdateSurveyAttribute, { s: sessionID, sid: sid, name: 'published', value: 'true'}, function(res) {
        if(res.error)
        {
            miniErrors('#thebuilder', res.error);
        }
        else
        {
            var pcredits = res.UpdateSurveyAttribute.public_credits;
            $('#thebuilder').hide();
            $('#publishedView').show();
            $('#distrbuteIt').click(function(){
                $('#tabs').tabs( 'select' , 2); 
            });
            $('#getaurl').click(function(){
                getPublicURL(sid, 'publishedView', pcredits);
            }); 
        }
    });
}
function getPublicURL(sid, div, pcredits)
{
    var htm = '<div id="getPublicDiv"><h2>Get a URL</h2>';
        htm += '<div id="urlDiaImage">&nbsp;</div>';
        htm += '<div>With a URL, you will be able to distribute your survey anywhere you want.</div>';
        htm += 'You will be charged '+pcredits+' credits to do this. Do you wish to proceed?';
        htm += '<input type="button" value="Yes" id="yesProceed" class="standard_btn small_button"/>';
        htm += '<a id="noProceed">No</a>';
        htm += '</div>';
    var perc = '50%';
    if(div == 'yourPublishedSurveys')
    {
        perc = '61%';
    }
    $('#'+div).block({
        overlayCSS:
        {
            backgroundColor: '#292929',
            opacity: 0.5
        },
        css: {
            color: '#000',
            width: perc,
            backgroundColor: '#fff',
            textAlign: 'left',
            left: '10px'
        },
        message: htm
    });
    $('#noProceed').click(function(){
        $('#'+div).removeClass('heightbig');
        $('#'+div).unblock();
    });
    $('#yesProceed').click(function(){
        $.getJSON(GetPublicSurveyUrl, {s: sessionID, survey_id: sid}, function(res){
            if(res.error)
            {
                $('#'+div).unblock();
                miniErrors('#'+div, res.error);                
            }
            else
            {
                setUserCreditsLeft('creditsLeft');
                var days = res.GetPublicSurveyUrl.expiry;
                var url = res.GetPublicSurveyUrl.url;
                var text = res.GetPublicSurveyUrl.title;
                var htm = '<div id="getPublicDiv"><h2>Get a URL</h2>';
                    htm += '<div class="bold">Your URL has been generated and will be active for next '+days+' days.</div>';
                    htm += '<div>You can see your public URLs under Home tab - Public Surveys.</div>'
                    htm += '<div>Your public URL <br /><input class="regularfield" id="publicUrl" type="text" readonly="true" value="'+url+'" /></div>';
                    htm += '<div>Share your survey now!</div>';
                    htm += '<div><a id="fbShare">&nbsp;</a>';
                    htm += '<a id="twShare">&nbsp;</a>';
                    htm += '<a id="sendMail" href="mailto:?subject='+text+'&body='+url+'">&nbsp;</a></div>';
                    htm += '<div>&nbsp</div>';
                    htm += '<div><a id="done">Done</a></div>';
                $('#'+div).unblock();
                $('#'+div).block({
                    overlayCSS:
                    {
                        backgroundColor: '#3e3e3e'
                    },
                    css: {
                        color: '#000',
                        width: '50%',
                        backgroundColor: '#fff',
                        textAlign: 'left',
                        left: '10px'
                    },
                    message: htm
                });
                $('#fbShare').click(function(){
                    window.open('http://www.facebook.com/sharer.php?u='+url+'&t='+text);
                });
                $('#twShare').click(function(){
                    window.open('http://twitter.com/home?status='+text+' '+url);
                });
                $('#done').click(function(){
                    $('#'+div).removeClass('heightbig');
                    $('#'+div).unblock();
                });
                $('#publicUrl').click(function(){
                    $('input#publicUrl').select();
                });
            }
        }); 
    });
}
function ListNewSurveys(head){         
    $.getJSON(GetActiveSurveys, { s: sessionID }, function(json){
        if(json.error)
        {
            miniErrors('#buildermenu', json);  
            return false;
        }
        var actSurveys = json.GetActiveSurveys.surveys;
        if(actSurveys)
        {
            if(head)
            {
                $('#newsurveylist').append('<tr><th>Id</th><th>Title</th><th>Last Modified</th><th>&nbsp;</th><th>&nbsp;</th><th>&nbsp;</th></tr>');
            }
		    $.each(actSurveys, function(i, currentsurvey){ // For each survey...
                var surveyID = currentsurvey.id;
                var surveyRef = currentsurvey.reference;
                var surveyName = currentsurvey.title;
                var surveyResponses = currentsurvey.responses;
                var surveyModified = currentsurvey.modified_date;
                var titleShort = surveyName;
                if(surveyName.length > 43)
                {
                    titleShort =  surveyName.substr(0, 40)+'...';
                }
                var currentListing = '<tr id="surveyRow_'+surveyID+'"><td>'+surveyRef+'</td>';
                    currentListing += '<td>'+titleShort+'</td><td>'+surveyModified+'</td>';
                    currentListing += '<td><span id="pleaseEdit_'+surveyID+'"class="linkstyling edit_survey" title="Update survey details">Edit</span></td>';
                    currentListing += '<td><span id="pleaseCopy_'+surveyID+'"class="linkstyling copy_survey" title="Create a copy of this survey">Copy</span></td>';
                    currentListing += '<td><span id="pleasedelete_'+surveyID+'" class="linkstyling" title="Delete survey">Delete</span></td>';
                    currentListing += '<td><span id="testRun_'+surveyID+'" class="linkstyling surveyTestRun" title="Test your survey">Test</span></td>';
                    currentListing += '</tr>';
                $('tr#surveyRow_'+surveyID).remove();
                $('table#newsurveylist').append(currentListing);
                $('tr#surveyRow_'+surveyID).data('sid',surveyID); 
                $('tr#surveyRow_'+surveyID).data('surveyName',surveyName);
                $('span#pleaseEdit_'+surveyID).click(function(){
                    var targetSurvey = $('tr#surveyRow_'+surveyID).data('sid');
                    editSurvey = targetSurvey;
                    buildType = 'edit';
                    loadSurvey(buildType);
                });
                
                //Copy Survey
                $('span#pleaseCopy_'+surveyID).click(function(){
                    var surveyId = $('tr#surveyRow_'+surveyID).data('sid');
                    $.getJSON(ReuseSurvey, { s: sessionID, sid: surveyId }, function(json){
                        if(json.error)
                        {
                            return false;
                        }
                        ListNewSurveys(false);
                    });
                });

                $('span#pleasedelete_'+surveyID).click(function(){
                    var targetSurvey = $('tr#surveyRow_'+surveyID).data('sid');
                    var targetSurveyName = $('tr#surveyRow_'+surveyID).data('surveyName');
                    var theMessage = '<h3 class="confirmdeletetitle">'+targetSurveyName+'</h3>';
                        theMessage += 'Are you sure you want to delete this survey?<p class="confirmdialogueoptions">';
                        theMessage += '<span id="delete_'+targetSurvey+'" class="linkstyling lighten confirm_delete" title="'+targetSurvey+'">yes</span> ';
                        theMessage += '<span id="cancel_'+targetSurvey+'" class="linkstyling lighten cancel_delete">no</span></p>';
                    $('div#buildermenu').block({css: {color: '#f42c52'},message:theMessage});
                    
                    $('span#cancel_'+targetSurvey).live('click', function(){
                        $('div#buildermenu').unblock();
                    })
            
                    $('span#delete_'+targetSurvey).live('click', function(){
                        var surveyID = $(this).attr('title');
                        deleteSurvey(surveyID);
                        return false;
                    });
                });	
                //Test Run
                $('#testRun_'+surveyID).click(function(){
                    var sid = $('tr#surveyRow_'+surveyID).data('sid');
                    $('#buildermenu').addClass('height');
                    sendTestRunSMS(sid, 'buildermenu');
                });
                $('div#buildermenu').unblock();
	 	    });
        }
        else
        {
            $('#newsurveylist').append('<tr><td class="error">No saved surveys. Click Build New Survey to start creating surveys</td></tr>');
        }
	});
}

function setBuildSurvey(divId)
{
    var htm = '<label class="block">Enter Survey title: </label>';
        htm += '<input type="text" id="survey_title" />';
        htm += '<label class="block bold">Allow multiple responses:</lable>';
        htm += '<label class="block"><input type="radio" name="allow_multiple_response" value="no" checked="true" /> No, allow only one response per user</label>';
        htm += '<label class="block"><input type="radio" name="allow_multiple_response" value="yes" /> Yes, allow multiple response per user</label>';
        htm += '<p class=""><input type="button" class="standard_btn small_button" id="addSurveyTitle" value="Create">';
        htm += '<span class="linkstyling lighten marginleft" id="cancelSurveyTitle">cancel</span></p>';
    $('div#'+divId).block({
        overlayCSS: {
            backgroundColor: '#292929',
            opacity: 0.5
        },
        css: {
            backgroundColor: '#fff',
            textAlign: 'left',
            left: '10px',
            color: '#000',
            width: '40%'
        },
        message:htm});
    $('#survey_title').focus();
    $('#addSurveyTitle').click(function(){
        var title = $('#survey_title').val();
        var surveyDesc = "Click here to edit/update your Survey's start message.";
        var surveyEndMsg = "Click here to edit/update your Survey's end message.";
        var allowMultipleResp = $("input[@name='allow_multiple_response']:checked").val();
        $.getJSON(CreateNewSurvey, {s: sessionID, title: title, desc: surveyDesc, end_message: surveyEndMsg, allow_multiple: allowMultipleResp}, function(res){
            if(res.error)
            {
                $('div#'+divId).unblock();
                miniErrors('div#'+divId, res.error);
                return false;
            }
            $('div#'+divId).unblock();
            editSurvey = res.CreateNewSurvey.id;
            setNewSurveyThemes(editSurvey);
            if(divId == 'yoursurveys')
            {
                buildType = 'edit';
                $('#tabs').tabs( 'select' , 1 );
            }
            else
            {
                loadSurvey('edit');
            }
        });
    });
    $('#cancelSurveyTitle').click(function(){
        $('div#'+divId).unblock();
        $('div#'+divId).removeClass('height');
    }); 
}
function builderLoad(buildType){
    $('#question_list').empty();
    //$('div#thebuilder').block();
    $('div#thebuilder').data('currentSurvey', '');
    $('div#builder_side_tabs').tabs();
    $('div#builder_side_tabs').tabs('select', 1);
    if(buildType == 'new' || buildType == 'edit')
    {
        loadSurvey(buildType);
    }
    else
    {
        ListNewSurveys(true);
    }
    $('#buildnewsurvey').click(function(){
        $('#buildermenu').addClass('height');
        setBuildSurvey('buildermenu');    
    }); 
    
    $('div#start_message').click(function(){
        $('.currentQuestion').removeClass('currentQuestion');
        $('div#start_message').addClass('currentQuestion');
         if(!$('#addanswer').hasClass('inactive')){
            $('#addanswer').addClass('inactive');
         }
         $('div#survey_contents').hide("slide", {direction: "up"}, 100, function(){
            $('div#survey_contents').show("slide", {direction: "up"}, 200);
            $('div.surv_content').each(function(){
                if($(this).attr('id')!='survey_start_message'){
                    $(this).hide();
                } else {
                    $(this).show()
                }
            });
        });
    });
    $('div#end_message').click(function(){
        $('.currentQuestion').removeClass('currentQuestion');
        $('div#end_message').addClass('currentQuestion');        
        if (!$('#addanswer').hasClass('inactive')){
            $('#addanswer').addClass('inactive');
        }
        $('div#survey_contents').hide("slide", {direction: "up"}, 100, function(){
            $('div#survey_contents').show("slide", {direction: "up"}, 200);
            $('div.surv_content').each(function(){
                if($(this).attr('id')!='survey_end_message'){
                    $(this).hide();
                } else {
                    $(this).show();
                }
            });
        });
    });
    $('input#addanswer').click(function(){
        if ($('#addanswer').hasClass('inactive')){
            return false;
        } else{
            addAns();
        }
    });
    $('#add_question').click( function(){
        if ($('#add_question').hasClass('inactive')){
            return false;
        } else{
            AddSurveyQn();
        }        
    });
    $('#exportTempAnswers').click(function(){
        var surveyId = $('div#thebuilder').data('currentSurvey');
        var questionId = $('div#survey_wrap').data('currentQuestion'); 
        if(! questionId)
        {
            miniErrors('#survey_wrap', 'Please select a Question');
            return false;
        }
        //Check Answer selection
        var ansIdArr = Array();
        $('input[name=ansTemp]:checked').each(function(i) {            
            ansIdArr[i] = this.value;            
        });
        if(ansIdArr.length == 0)
        {
            miniErrors('#tempAnswerList', 'Please select Answers');
            return false;
        }
        var ansIds = ansIdArr.join(',');
        //Add Answers to Questions
        $.getJSON(AddTemplateAnswers, {s: sessionID, answers_id: ansIds, survey_id: surveyId, question_id: questionId}, function(res){
            if(res.error)
            {
                return false;
            }
            var answerArray = res.AddTemplateAnswers.answers;
            if(answerArray)
            {
                $('p#question_no_answers').hide();
                displayAnswers(answerArray);
            }            
        });
    }); 
    $('#checkAnsAll').click(function(){
        $('input[name=ansTemp]').attr('checked', true);
    });   
    $('#checkAnsNone').click(function(){
        $('input[name=ansTemp]').attr('checked', false);
    });
    $("#tempAnswerList").droppable({
        drop: function(event, ui) {
            var licount = $("#tempAnswerList li").length;
            licount = licount+1;            
            var liId = ui.helper.attr("id");
            var ansTxt = $('#'+liId+' div.answer_text_row').html();
            if(ansTxt)
            {
                $.getJSON(AddAnswerTemplate, {s: sessionID, answer:  ansTxt}, function(res) {
                    if(res.error)
                    {
                        miniErrors('#thebuilder', res.error);
                        return false;
                    }
                    $('#checkAllOpt').show();
                    if($('#defaultTemp').length)
                    {
                        $("#tempAnswerList").html('');
                    }
                    var tempId = res.AddAnswerTemplate.id;
                    var htm = '<li id="ansTemp'+tempId+'">';
                        htm += '<div class="answer_template">';
                        htm += '<div class="answer_checkbox"><input type="checkbox" name="ansTemp" value="'+tempId+'" /></div>';
                        htm += '<div class="editable">'+ansTxt+'</div>';
                        htm += '<div id="tempAnsDelete'+tempId+'" class="delete_btn"></div>';
                        htm += '<div class="clear"></div>';
                        htm += '</div></li>';
                    $("#tempAnswerList").append(htm);
                    $('#ansTemp'+tempId).data('ansTempId', tempId);
                    $('#ansTemp'+tempId).data('ansTxt', ansTxt);
                    $('#tempAnsDelete'+tempId).click(function(){
                        confirmDeleteTemplateAnswer(this);
                    });
                });            
            }
        }
    });
    $("#tempAnswerList").sortable({
        stop: function(event, ui) {
            var currPosition = $('#tempAnswerList li').index(ui.item);
            var ansId = ui.item.data('ansTempId');
            currPosition = currPosition+1;
            $.getJSON(UpdateTemplateAnswerPosition, {s: sessionID, answer_id: ansId, curr_position: currPosition}, function(res){
                //
            });
        }
    });
    $("#tempAnswerList").disableSelection();

    $('#setings').click(function(){
        
    });
}

function loadSurvey(buildType) {
    if (buildType == 'edit') {
        initEditSurvey(editSurvey);
        editableBits();
        builderBack();
    } else if(buildType == 'new'){
        initNewSurvey();
        editableBits();
        builderBack();
    }
    //Load Template Answers
    loadTemplateAnswers();
}
function  loadTemplateAnswers()
{
    $.getJSON(GetTemplateAnswers, {s: sessionID}, function(res){
        var answers = res.GetTemplateAnswers.answers;
        if(answers.length)
        {   
            $('#checkAllOpt').show();
            $("#tempAnswerList").html('');
            $.each(answers, function(i, answer){
                var ansId = answer.id;
                var ansTxt = answer.answer;
                var ansPos = answer.position;
                var ansCnt = i+1;
                var htm = '<li id="ansTemp'+ansId+'">';
                    htm += '<div class="answer_template">';
                    htm += '<div class="answer_checkbox"><input type="checkbox" name="ansTemp" value="'+ansId+'" /></div>';
                    htm += '<div class="editable">'+ansTxt+'</div>';
                    htm += '<div id="tempAnsDelete'+ansId+'" class="delete_btn"></div>';
                    htm += '<div class="clear"></div>';
                    htm += '</div></li>';
                $("#tempAnswerList").append(htm);
                $('#ansTemp'+ansId).data('ansTempId', ansId);
                $('#ansTemp'+ansId).data('ansTxt', ansTxt);
                $('#tempAnsDelete'+ansId).click(function(){
                     confirmDeleteTemplateAnswer(this);
                });
            });   
        }
        else
        {
            $('#checkAllOpt').hide();
            $("#tempAnswerList").html('<div id="defaultTemp">Drag your answers in here to use them later!</div>');
        }
    });
}
function confirmDeleteTemplateAnswer(obj){        
    var ansTempIndex = $(obj).parent().parent().attr("id");
    var ansId = $('#'+ansTempIndex).data("ansTempId");
    var ansTxt = $('#'+ansTempIndex).data("ansTxt");
    
    var theMessage = 'Are you sure you want to delete the answer "'+ansTxt+'"? ';
        theMessage += '<p><span class="linkstyling lighten confirm_delete_ans">yes</span> <span class="linkstyling lighten cancel_delete_ans">no</span></p>';
        $('#builder_side_tab_wrap').block({css: {color: '#f42c52', width: '75%'},message:theMessage});
        $('.confirm_delete_ans').click(function(){
            deleteTemplateAnswer(ansId, ansTempIndex);
        })    
        $('.cancel_delete_ans').click(function(){
            $('#builder_side_tab_wrap').unblock();
        })                
}
function deleteTemplateAnswer(ansId, ansTempIndex)
{   
    $.getJSON(DeleteTemplateAnswer, {s: sessionID, answer_id: ansId}, function(res){
        if(res.error)
        {
            $('#tempAnswerList').unblock();
            return false;
        }
        $('#'+ansTempIndex).remove();
        $('#builder_side_tab_wrap').unblock();
        var licount = $("#tempAnswerList li").length;
        if(licount == 0)
        {
            $('#checkAllOpt').hide();
            $("#tempAnswerList").html('<div id="defaultTemp">Drag your answers in here to use them later!</div>');
        }
    });
}
function builderBack(){
    $('span.page_title').addClass('linkstyling');
    $('span.page_title.linkstyling').click(function(){
        if ($('span.page_title').hasClass('linkstyling')){
            $('span.page_title').removeClass('linkstyling');
            $('#thebuilder').hide();
            $('#publishedView').hide();
            $('#buildermenu').empty().append('<h2>Saved Surveys</h2><table id="newsurveylist"></table>').show();
            $('#buildnewsurvey').show();
            $('#surveyTitleHead').html('');
            $('#buildermenu').removeClass('height');
            ListNewSurveys(true);
        }
    });
}
//DISTRIBUTOR////////////////////////////////////////////////////////////////////////////////////////
function distributorQtips(){
	$('#msids').qtip({
               content: {text: 'Numbers and commas only.'}, // Set the tooltip content to the current corner
               position: {
                  corner: {
                     tooltip: 'bottomRight', // Use the corner...
                     target: 'topRight' // ...and opposite corner
                  }
               },
               show: { delay: 0, when: { event: 'focus',fixed: false } },
               hide: { delay: 0, when: { event: 'blur',fixed: false } },
               style: {
                  border: {
                     width: 1,
                     radius: 3
                  },
                  textAlign: 'center',
                  tip: true,
                  name: 'green'
               }
            });
            
	$('#message').qtip({
               content: {text: 'Keep it to a maximum of 129 characters.'}, // Set the tooltip content to the current corner
               position: {
                  corner: {
                     tooltip: 'bottomRight', // Use the corner...
                     target: 'topRight' // ...and opposite corner
                  }
               },
               show: { delay: 0, when: { event: 'focus',fixed: false } },
               hide: { delay: 0, when: { event: 'blur',fixed: false } },
               style: {
                  border: {
                     width: 1,
                     radius: 3
                  },
                  textAlign: 'center',
                  tip: true,
                  name: 'green'
               }
            });            
}

function handleDistribution(){
		    function DistributeSurveyRequest(formData, jqForm, options) {
	            $('div#thedistributor').block({message:"<img src=\"imgs/loader_small.gif\" alt=\"loading...\" /><h4><br/></h4>"});
	        }
	        
	        function processDistributeSurvey(data) { //determines what to display when user is logging in.
                if (data.error){
                	$('div#thedistributor').unblock();
                    miniErrors('div#thedistributor', data);
                } else {
		                	$('div#thedistributor').unblock();
		                	$('div#thedistributor').block({css: {color: '#25c058'},message:"Distribution was successful."+olclicktocontinue});
                            setUserCreditsLeft('creditsLeft');

                }
            }
            
            var DistributeSurveyOptions = { //These options are fed into the Login ajaxSubmit function.
                    url:  DistributeSurvey,
                	dataType:  'jsonp',
                    success:   processDistributeSurvey,
                    beforeSubmit:  DistributeSurveyRequest
            };              
			
            var l = $('#distribute_survey').validate({
                    submitHandler: function(form) {
                        $(form).ajaxSubmit(DistributeSurveyOptions);
                    }
            });
}

function distributorLoad(){

    var publicSurveyCredits = 0;
    $.getJSON(GetConfigValues, {s: sessionID}, function(res) {
        if(!res.error)
        {
            publicSurveyCredits = res.GetConfigValues.config.public_survey_credits;
        }
    });

    //Checking User credit status
    if(getCookieDetails('free_user') == "false")
    {
        $.getJSON(GetCreditBalance, { s: sessionID }, function(response) {
            if(response.error) {
                miniErrors('div#Home', response);
                return false;
            }
            var credits = response.GetCreditBalance.credits;
            if(credits <= 0)
            {
                $('#buyCreditMessage').show();
            }
            $('#distBuyCredits').click(function(){
                $('#tabs').tabs( 'select' , 4);
            });
        });
    }

    $.getJSON(GetPublishedSurveys, { s: sessionID, all:true }, function(json){
        var userSurveys = json.GetPublishedSurveys.surveys;
        if(userSurveys.length)
        {
            $('#thedistributor').removeClass('content_box');
            var htm = '<div id="distributeBox" class="content_box"><form id="distribute_survey" method="get"><fieldset>';
                htm += '<span class="bold">Distribute via SMS</span>';
                htm += '<label class="" for="surveydropdown">Choose a published survey</label><SELECT id="surveydropdown" name="sid"></SELECT>';
                htm += '<label for="msids">Enter some numbers seperated by comma ( , )</label><textarea rows="2" cols="20" id="msids" class="required" name="msids"></textarea>';
                htm += '<div class="clearer"><a id="uploadCsv">Upload Numbers</a> (csv format)</div>';
                htm += '<div class="clearer"><label><a id="importNumbers">Import from Eventbrite</a></label></div>';
                htm += '<label for="message">Enter a short message - <span id="counter"></span> characters left.</label>';
                htm += '<textarea rows="2" cols="20" id="message" class="required" name="message"></textarea>';
                htm += '<input type="hidden" class="sessionfield" name="s" value="">';
                htm += '<input type="submit" value="Distribute!" class="standard_btn small_button"/>';
                htm += '</fieldset></form></div>';
                htm += '<div id="smsSendStatusDiv" class="content_box"><div class="bold">Distribute anywhere</div>';
                htm += '<p id="pricePublic">For '+publicSurveyCredits+' credits, get a URL that you can share anywhere.</p>';
                htm += '<p><select id="publicSurveysDist"></select>';
                htm += '<div class="clearer"></div>';
                htm += '<input id="getUrlDist" type="submit" value="Get a URL" class="standard_btn small_button"/></div>';

                $('#thedistributor').prepend(htm);
                $('#message').apTextCounter({
                    tracker: '#counter',
                    maxCharacters: 130
                });
                $.each(userSurveys, function(i, currentsurvey){
                    var surveyID = currentsurvey.id;
                    var surveyName = currentsurvey.title;
                    var surveyRef = currentsurvey.reference;
                    surveyTitle = surveyRef+' - '+surveyName
                    if(surveyTitle.length > 42)
                    {
                        surveyTitle = surveyTitle.substring(0,39)+'...';
                    }                    
                    $('SELECT#surveydropdown').append('<option value="'+surveyID+'">'+surveyTitle+'</option>');
                    $('select#publicSurveysDist').append('<option value="'+surveyID+'">'+surveyTitle+'</option>');
                });
                $('input.sessionfield').val(sessionID);
                distributorQtips();
                handleDistribution();
                //$('#msids').numeric({allow:","});
                uploadCSV();
                $('#importNumbers').click(function(){
                    importNumbers();
                });
                $('#getUrlDist').click(function(){
                    var sid = $('#publicSurveysDist').val();
                    if(sid)
                    {
                        getPublicURL(sid, 'thedistributor', publicSurveyCredits);    
                    }
                });
        }
        else
        {
            $('#thedistributor').addClass('content_box');
            $('#thedistributor').html('You do not have any published surveys. Click <a id="buildSurv">Builder</a> to create new or publish your surveys.');
        }
        $('#buildSurv').click(function(){
            $('#tabs').tabs('select', 1);
        });
    });
}
function importNumbers()
{
    $.getJSON(GetEventbriteEvents, {s: sessionID}, function(res){
        if(res.error_code == 'ERROR_UPDATE_KEY')
        {
            $('div#distributeBox').block({css: {color: '#25c058', width: '80%'},message: res.error + olclicktocontinue});
            return false;
        }
        else if(res.error)
        {
            miniErrors('#distribute_survey', res.error);
            return false;
        }

        var events = res.GetEventbriteEvents.events;
        if(events.length == 0)
        {
            miniErrors('#distribute_survey', 'Failed to retrieve events from Eventbrite. Please try again.');
            return false;
        }
        else
        {
            var htm = '<div clas="dialogBox"><b>Choose an Event</b>';
                htm += '<label>Attendees & Event Name</label>';
                htm += '<select id="eventList">';
                $.each(events, function(i, eve){
                    htm += '<option value="'+eve.id+'">('+eve.participants+') '+eve.title+'</option>';
                });
                htm += '</select>';
                htm += '<table><tr><td><input id="importDone" type="button" value="Done" class="standard_btn small_button"/></td>';
                htm += '<td><span class="linkstyling lighten importCancel">Cancel</span></td></tr></table>';
                htm += '</div>';
            $('#distribute_survey').block({
                overlayCSS: 
                { 
                    backgroundColor: '#3e3e3e' 
                },
                css: {
                    color: '#000', 
                    width: '80%',
                    backgroundColor: '#fff',
                    textAlign: 'left',
                    left: '10px'
                }
                ,message:htm
            });
            $('#importDone').click(function(){
                var eveId = $('#eventList').val();
                importEventContacts(eveId);
            });
            $('.importCancel').click(function(){
                $('#distribute_survey').unblock();
            });
        }
    });
}
function importEventContacts(eveId)
{
    $.getJSON(ImportEventContacts, {s: sessionID, event_id: eveId}, function(res) {
        if(! res.error)
        {
            var exMsids = $('#msids').val();
            var msids = res.ImportEventContacts.msids;
            msids = msids.join(', ');
            if(exMsids.length)
            {
                msids = exMsids+', '+msids;
            }
            $('#msids').val(msids);
            $('#distribute_survey').unblock();
        }
    });
}
function uploadCSV()
{
    new AjaxUpload('#uploadCsv', {
      // Location of the server-side upload script
      // NOTE: You are not allowed to upload files to another domain
      action: ParseCsvMsids,
      // File upload name
      name: 'csv_msids',
      // Additional data to send
      data: {
        s: sessionID
      },
      // Submit file after selection
      autoSubmit: true,
      // The type of data that you're expecting back from the server.
      // HTML (text) and XML are detected automatically.
      // Useful when you are using JSON data as a response, set to "json" in that case.
      // Also set server response type to text/html, otherwise it will not work in IE6
      responseType: false,
      // Fired after the file is selected
      // Useful when autoSubmit is disabled
      // You can return false to cancel upload
      // @param file basename of uploaded file
      // @param extension of that file
      onChange: function(file, extension){},
      // Fired before the file is uploaded
      // You can return false to cancel upload
      // @param file basename of uploaded file
      // @param extension of that file
      onSubmit: function(file, extension) {
            if (! (extension && /^(csv)$/.test(extension)))
            {
                    // extension is not allowed
                    var errorMSG = 'Sorry, File must be in CSV format';
                    miniErrors('div#thedistributor', errorMSG);
                    // cancel upload
                    return false;
            }
      },
      // Fired when file upload is completed
      // WARNING! DO NOT USE "FALSE" STRING AS A RESPONSE!
      // @param file basename of uploaded file
      // @param response server response
      onComplete: function(textStatus,data) {
        data = data.replace('<pre>', '').replace('</pre>', '');
        var inJSON = jQuery.toJSON(data);
        var msids = inJSON.ParseCsvMsids.msid;
        var exMsids = $('#msids').val();
        msids = msids.join(',');
        if(exMsids.length)
        {
            msids = exMsids+','+msids;
        }
        $('#msids').val(msids);
      }
    }); 
}

//ACCOUNT MANAGEMENT/////////////////////////////////////////////////////////////////////////////////
    function managementLoad(){ //loads the management interfaces
		$('div#userdetails').block();
		$('input.sessionfield').val(sessionID);
        $('#applicationKeys').hide();
        $.getJSON(GetUserData, { s: sessionID }, function(json){
            if (json.error){
                miniErrors(json);
                return false;
            }
            $('input#reg_firstname').val(json.GetUserData.first_name);
            $('input#reg_lastname').val(json.GetUserData.last_name);
            $('input#reg_mobile').val(json.GetUserData.mobile);
            $('#eventbriteApi').val(json.GetUserData.eventbrite_api);
            $('div#userdetails').unblock();
            var virePricing = json.GetUserData.view_pricing_option;
            //Check Survey Pricing option view
            if(virePricing == "true")
            {
                $('#usrSurPricing').show();
                if(getCookieDetails('free_user') == "false")
                {
                    $.getJSON(GetSurveyPricing, {s: sessionID}, function(response){
                        if(response.error)
                        {
                            return false;
                        }
                        var surveyPrices = response.GetSurveyPricing.pricing;
                        var htm = '<label>Choose an option</label>';
                        var currPricingId = getCookieDetails('survey_pricing_id');
                        $.each(surveyPrices, function(i, survey){
                            if(survey.userView == "true")
                            {
                                if(survey.id == currPricingId)
                                {
                                    htm += '<label><input type="radio" name="pricing" value="'+survey.id+'" checked="true" /> For SMS: '+survey.sms_cost+', Response: '+survey.response_cost+'</label>';
                                }
                                else
                                {
                                    htm += '<label><input type="radio" name="pricing" value="'+survey.id+'" /> For SMS: '+survey.sms_cost+', Response: '+survey.response_cost+'</label>';
                                }
                            }
                        });
                        htm += '<input type="button" id="accountPricing" value="Update" class="standard_btn small_button" />';
                        $('#usrPriceOpt').html(htm);

                        $('#accountPricing').click(function(){
                            var pricingId = $("input[name='pricing']:checked").val();
                            $.ajax({
                                type: "GET",
                                url: UpdateUserSurveyPricing,
                                dataType:  'jsonp',
                                data: ({survey_pricing_id: pricingId, s: sessionID}),
                                success: function(res) {
                                    if(res.error)
                                    {
                                        miniErrors('div#usrSurPricing', res); 
                                        return false;
                                    }
                                    createCookie('survey_pricing_id', pricingId);
                                    $('div#usrSurPricing').block({css: {color: '#25c058'},message:"You survey pricing has been updated."+olclicktocontinue});
                                    //loadUserPricing();
                                }
                            });
                        });
                    });
                }
                else
                {
                    $('#usrPriceOpt').html('<ul><li>Free User</li></ul>');
                }
            }
            else
            {
                $('#usrSurPricing').hide();
            }
        });
        
        function loadUserPricing()
        {
            $.getJSON(GetUserPricing, {s: sessionID}, function(response){
                if(response.error)
                {
                    return false;
                }
                var smscost = response.GetUserPricing.smsCost;
                var rescost = response.GetUserPricing.responseCost;
                var htm = '<ul>';
                if(smscost > 0)
                {
                    htm += '<li>SMS Cost: '+smscost+'</li>';
                }
                if(rescost > 0)
                {
                    htm += '<li>Response Cost: '+rescost+'</li>';
                }
                htm += '</ul>';
                $('#usrPriceOpt').html(htm);
            }); 
        }
        function detailupdateRequest(formData, jqForm, options) {
                        $('#rego_box').hide();
                        $(".reg_fail").remove();
                        $('div#userdetails').block();
            }

        function passwordupdateRequest(formData, jqForm, options) {
                        $(".form_success").remove();
                        $(".form_fail").remove();
                        $('div#userpassword').block();
            }


        function processDetailUpdate(data) { //determines what to display when user is registering.
                if (data.error){
                    $.jGrowl(data.error, { life: 3000 });
                } else {
                	$('div#userdetails').block({css: {color: '#25c058'},message:"Your details have been updated."+olclicktocontinue});
                    var fullname = data.UpdateUser.name;
                    $('#longinedUserName').html(fullname);
                    createCookie('user_fullname', fullname);
                }
            }


        function processPasswordUpdate(data) { //determines what to display when user is logging in.
                if (data.error){
                    $.jGrowl(data.error, { life: 3000 });
                } else {
                	$('div#userpassword').block({css: {color: '#25c058'},message:"Your password has been updated."+olclicktocontinue});
                }
            }

                var detailUpdateOptions = {
                    url: UpdateUser,
                    dataType:  'jsonp',
                    success:   processDetailUpdate,
                    beforeSubmit:  detailupdateRequest
                };

                var passwordUpdateOptions = {
                    url: ChangePassword,
                    dataType:  'jsonp',
                    success:   processPasswordUpdate,
                    beforeSubmit:  passwordupdateRequest
                };


                var r = $("#detail_update").validate({
                    submitHandler: function(form) {
                        $(form).ajaxSubmit(detailUpdateOptions);
                    }
                });


                var l = $("#password_update").validate({
                    rules: {
                        reg_new_password: {equalTo: "#reg_password"}
                    },
                    submitHandler: function(form) {
                        $(form).ajaxSubmit(passwordUpdateOptions);
                    }
                });

                $('#apikeyform').validate({
                    submitHandler: function(form) {
                        $(form).ajaxSubmit({
                            url: UpdateEventbriteApi,
                            dataType:  'jsonp',
                            success: function(res) {
                                if(res.error)
                                {
                                    miniErrors('#briteapi', res.error);
                                }
                                else
                                {
                                    $('div#briteapi').block({css: {color: '#25c058'},message:"Your api has been updated."+olclicktocontinue});
                                }
                            }
                        });
                    }
                });
        
    }


//EXECUTE EXECUTE EXECUTE///////////////////////////////////////////////////////////////////////////
        var loginstatus = $.cookie('mpoll_cookie'); // assigns a value that can be checked
        if (loginstatus != null){ // checks if user is logged in
            liContents();
        } else { //if user is not logged in
            nliLoaded(); // loads jQuery for not logged in pages.
        }
//BUY CREDITS management///////////////////////////////////////////////////////////////////////////////
    function buycreditsLoad(){ //loads the management interfaces
        $('div#userdetails').block();
        $('input#userSession').val(sessionID);
        $('input#sessionid').val(sessionID);
        //Allow onlu intger values for Credits buy
        $("input.creditsBuy").numeric(); 
        $('#buyCreditsPayment').hide();
        var hostURL = baseURL;//window.location.protocol+'//'+ window.location.hostname;

        //Get User details
        var userPricingId = 0;
        $.getJSON(GetUserData, { s: sessionID }, function(response) {
            userPricingId = response.GetUserData.survey_pricing_id;
            var viewPricing = response.GetUserData.view_pricing_option;
            if(viewPricing == "true")
            {
                if(userPricingId <= 0)
                {
                    //Get Pricing options
                    $.getJSON(GetSurveyPricing, { s: sessionID }, function(json) {
                        var surveyPricing = json.GetSurveyPricing.pricing;
                        var priceHtm = '';
                        var vHtm = '';
                        $.each(surveyPricing, function(i, price) {
                            var pid = price.id;
                            var smsCost = price.sms_cost;
                            var resCost = price.response_cost;
                            if(price.userView == "true")
                            {
                                priceHtm += '<label><input type="radio" class="" name="userPricingId" id="userpr_'+pid+'" value="'+pid+'" /> SMS: '+smsCost+', Response: '+resCost+'</label>';
                                vHtm += '<label><input type="radio" name="voucherPricingId" id="vprice_'+pid+'" value="'+pid+'" /> SMS: '+smsCost+', Response: '+resCost+'</label>';
                            }
                        });

                        $('#userPricingList').html(priceHtm);
                        $('#voucherPricingList').html(vHtm);
                        if(userPricingId == 0)
                        {
                            $('#userpr_1').attr('checked', true);
                            $('#vprice_1').attr('checked', true);
                        }
                    });
                }
                else
                {
                    $('#userPricingOptions').hide();
                    $('#voucherPricing').hide();
                }
            }
            else
            {
                $('#userPricingOptions').hide();
                $('#voucherPricing').hide();
            }
        });

        //Paypal Request success
        if(purchaseToken && payerId)
        {
            $('#buyCreditsForm').hide();
            $.ajax({
                type: "POST",
                url: baseURL+'/billing/getExpressCheckoutDetails.php',
                dataType: "json",
                data: ({token: purchaseToken, sessionid: sessionID}),
                success: function(response) {
                    if(response.error)
                    {
                        miniErrors('div#buyCreditsMore', response);
                        return false;
                    }
                    var token = response.TOKEN;
                    var payerid = response.PAYERID;
                    var amount = response.AMT;
                    var currcode = response.CURRENCYCODE; 
                    $('#buyCreditsPayment').show();
                    var htm = '<tr><th>Description</th><th>Credits</th><th>Rate</th><th>Subtotal</th><th>Tax</th><th>Total</th></tr>';
                        htm += '<tr><td>'+response.L_NAME1+'</td><td>'+response.L_QTY1+'</td><td>'+response.L_AMT1+'</td><td>'+response.ITEMAMT+'</td>';
                        htm += '<td>'+response.L_TAXAMT1+'</td><td>'+response.AMT+'</td></tr>';
                    $('#listItems').html(htm);
                    //Do Express Checkout payment
                    $('#payCreditsAmount').click(function (){
                        $.blockUI();
                        $('div#buyCreditsMore').block({css: {color: '#25c058'},message:"Please wait, while processiong your payment..."});
                        $.ajax({
                            type: "POST",
                            url: baseURL+'/billing/doExpressCheckoutPayment.php',
                            dataType: "json",
                            data: ({purToken: token, purPayerId: payerid, purAmount: amount, purCurrency: currcode, sessionid: sessionID}),
                            success: function(res){
                                $.unblockUI();
                                if(res.ACK == "Success")
                                {
                                    $('div#buyCreditsMore').block({css: {color: '#25c058'},message:"Your payment has been successfully completed."+olclicktocontinue});
                                }
                                else
                                {
                                    miniErrors('div#buyCreditsMore', res.L_LONGMESSAGE0)
                                    return false;
                                }
                            }
                        });
                    });
                }
            });
            return false;
        }
        else
        {
            setUserCreditsLeft('creditsLeft');
            //Read config values
            var defaultRate = 0;
            var defaultCredits = 0;
            var currencyCode = 'AUD';
            var taxRate = 0;
            var excludeTax = true;
            $.getJSON(GetCurrencyRates, {s: sessionID}, function(response){
                var rates = response.GetCurrencyRates.rates;
                if(rates)
                {
                    $.each(rates, function(shortCode, currency){
                        $('#currency').append('<option id="'+shortCode+'" value='+currency.rate+'>'+currency.name+'</option>');
                    });
                    
                    $.getJSON(GetConfigValues, {s: sessionID}, function(json) {
                        if(json.error)
                        {
                            return false;
                        }
                        defaultRate = json.GetConfigValues.config.survey_default_credit_rate;
                        defaultCredits = json.GetConfigValues.config.survey_default_credits_buy;
                        currencyCode = json.GetConfigValues.config.survey_default_currency;
                        taxRate = json.GetConfigValues.config.survey_tax_rate;
                        excludeTax = json.GetConfigValues.config.survey_exclude_tax;
                        $('#paypalCreditsBuy').data('paypalURL', json.GetConfigValues.config.paypal_url);
                        $('#defaultCredits').text(defaultCredits);
                        $('#creditsBuy').val(defaultCredits);
                        $('select#currency option#'+currencyCode).selected();
                        var currRate = $("#currency option:selected").val();
                        var currCode = $("#currency option:selected").attr("id");
                        $('#defaultCreditsBuy').val(defaultCredits);

                        calculateTotal(currCode, currRate);
                    });
                }
            });
            $('#currency').change(function(){
                var currRate = $("#currency option:selected").val();
                var currCode = $("#currency option:selected").attr("id");

                calculateTotal(currCode, currRate);
            });
        }
        
        //Checking user credit entry
        $('#creditsBuy').keyup(function (){
            var userInp = $('#creditsBuy').val();
            var defCred = $('#defaultCreditsBuy').val();
            if(userInp < defCred)
            {
                //$('#creditsBuy').val(defCred);
            }
            
            var currRate = $("#currency option:selected").val();
            var currCode = $("#currency option:selected").attr("id");

            calculateTotal(currCode, currRate);
        });
                
        //Calculate credits amount
        function calculateTotal(currCode, currRate)
        {
            var buyCredits = $('#creditsBuy').val();

            //Calculate Total in local currency
            var localSubTotal = roundNumber(buyCredits*(currRate*defaultRate));
            var localTax = 0;
            if(excludeTax == "false")
            {
                localTax = (localSubTotal*taxRate)/100;
            }
            var localTotal = roundNumber(localSubTotal+localTax);
            $('#subtotal').val(localSubTotal+' '+ currCode);
            $('#tax').val(localTax+' '+ currCode);
            $('#totalAmount').val(localTotal+' '+ currCode);

            //Calculate Total amounty in actual currency
            $.getJSON(GetTotalCreditAmount, { s: sessionID, credits: buyCredits}, function(json) {
                if (json.error)
                {
                    //miniErrors('div#buyCredits', json.error);
                    return false;
                }
                var subTotal = json.GetTotalCreditAmount.totalAmount - json.GetTotalCreditAmount.tax;
                var currency = json.GetTotalCreditAmount.currency;
                $('#subtotalAUD').val(subTotal+' ' + currency);
                $('#taxAUD').val(json.GetTotalCreditAmount.tax+' '+currency);
                $('#totalAmountAUD').val(json.GetTotalCreditAmount.totalAmount+' '+ currency);
                var defCred = parseInt($('#defaultCreditsBuy').val());
                if(buyCredits < defCred)
                {
                    buyCredits = defCred;
                }
                $('#totalCreditsAUD').html(buyCredits);
                $('#totalAmtAUD').html(json.GetTotalCreditAmount.totalAmount+' '+ currency);
            });
        }
        
        //To Update User pricing option
        function updateUserSurveyPricing(pricingId)
        {
            $.ajax({
                type: "GET",
                url: UpdateUserSurveyPricing,
                dataType:  'jsonp',
                data: ({survey_pricing_id: pricingId, s: sessionID}),
                success: function(res) {
                    if(res.error)
                    {
                        return false;
                    }
                    $('#userPricingOptions').hide();
                    $('#voucherPricing').hide();
                    createCookie('survey_pricing_id', pricingId);
                }
            }); 
        }
        function roundNumber(num)
        {
            return Math.round(num*Math.pow(10,2))/Math.pow(10,2);
        }
        $('#paypalSubmitBtn').click(function(){
            var userInp = $('#creditsBuy').val();
            var defCred = parseInt($('#defaultCreditsBuy').val());
            if(userInp < defCred)
            {
                miniErrors('div#buyCredits', 'Minimum credits purchase limit is '+defCred);
                return false;
                //$('#creditsBuy').val(defCred);
            }
            $.blockUI();
            $('div#buyCreditsForm').block({css: {color: '#25c058'},message:"Please wait. Your transaction is processing and will be redirected to PayPal"});
            var ajaxOpt = {
                url: baseURL+'/billing/setExpressCheckout.php',
                dataType:  'json',
                type: "POST",
                success: function(response) {
                    if(response.ACK == 'Success')
                    {
                        var purchaseToken = response.TOKEN;
                        var paypalURL = $('#paypalCreditsBuy').data('paypalURL');
                        window.location = paypalURL+purchaseToken;
                    }
                    else
                    {
                        miniErrors('div#buyCreditsForm', response.L_LONGMESSAGE0);
                        $.unblockUI();
                        return false;
                    }
                }
            }
            
            //Before submitting the form, update user pricing
            if(userPricingId <= 0) {
                var pricingId = $("input[name='userPricingId']:checked").val();
                updateUserSurveyPricing(pricingId);
            }
            $('#paypalCreditsBuy').validate({
                    submitHandler: function(form) {
                        $(form).ajaxSubmit(ajaxOpt);
                    }
            }); 
        });
        
        //VOUCHER 
        $('#buyVoucherCredits').click(function(){
            $('#voucherCreditsBuy').validate({
                submitHandler: function(form) {
                    //Before submitting the form, update user pricing
                    if(userPricingId <= 0) {
                        var pricingId = $("input[name='voucherPricingId']:checked").val();
                        updateUserSurveyPricing(pricingId);
                    }
                    //Submit form
                    $(form).ajaxSubmit({
                        url: RedeemVoucher,
                        dataType: "jsonp",
                        type: "POST",
                        success: function(response) {
                            if(response.error) {
                                miniErrors('div#buyCreditsForm', response);
                                return false;
                            }

                            $('div#creditsVoucher').block({css: {color: '#25c058'},message:"Your credit has been updated successfully."+olclicktocontinue});
                            setUserCreditsLeft('creditsLeft');
                            $('#voucherNumber').val('');
                        }
                    });
                }
            });
        });
    }
//END BUY CREDITS -----------------------------------------------------------------------------------------------
    
//ADMIN CONFIGURATION ///////////////////////////////////////////////////////////////////////////////////////////////
    function loadGlobalConfigurations() {
        $('#adminSurveyUsers').hide();
        $("#adminEditUser").hide();
        $('#adminSurveyUsage').hide();
        $('#adminCreditsUsage').hide();
        $('#adminPurchaseHistory').hide();
        $('#adminVoucherManage').hide();
        setAdminSelection('adminConfigs');
        $.getJSON(GetGlobalConfigurations, { s: sessionID }, function(json) {
            if(json.error)
            {
                miniErrors('div#adminConf', json);
                return false;
            }
            $.each(json.GetGlobalConfigurations.configurations, function(i){
                var confName = i;
                var confValue = this;
                var confList = '<tr><td>'+confName+' </td>';
                    confList += '<td id="'+confName+'_value">'+confValue+'</td>';
                    confList += '<td id="'+confName+'_action"><a id="'+confName+'" class="edit">edit</a></td></tr>';

                $('table#configList').append(confList);
            });
            //Edit
            $('a.edit').click(function() {
                var configName = $(this).attr('id');
                var configValue = $('#'+configName+'_value').html();
                $('td#'+configName+'_value').data(configName, configValue);
                $('#'+configName+'_value').html('<input type="text" id="'+configName+'_input" value="'+configValue+'" />');
                $('a.edit').hide();
                $('#'+configName+'_action').append('<input type="button" value="Save" class="small_button_save standard_btn" /> <a id="'+configName+'" class="cancel">Cancel</a>');
                $(".small_button_save").data('configname', configName);
                //Save
                $(".small_button_save").click(function (){
                    var configName = $(this).data('configname');
                    var confValue = $('#'+configName+'_input').val();
                    $.ajax ({
                        type: "GET",
                        url: UpdateGlobalConfigurations,
                        data: configName+"="+confValue+"&s="+sessionID,
                        dataType: "jsonp",
                        success: function(res){
                            if(res.UpdateGlobalConfigurations.error)
                            {
                                miniErrors('div#adminConf', json);
                                return false;
                            }
                            $('#'+configName+'_value').html(confValue);
                            $('.small_button_save').hide();
                            $('a.cancel').hide();
                            $('a.edit').show();
                        }
                    });
                });
                //Cancel
                $('a.cancel').click(function() {
                    var configName = $(this).attr('id');
                    var oldConfValue = $('td#'+configName+'_value').data(configName);
                    $('#'+configName+'_value').html(oldConfValue);
                    $('.small_button_save').hide();
                    $('a.cancel').hide();
                    $('a.edit').show();
                });
            });
        });
        
        //Survey Pricing
        loadSurveyPriceList();

        $('#savePricing').click(function(){
            var smsCost = $("input#smsCost").val();
            var resCost = $("input#responseCost").val();
            var priceId = $("input#priceId").val();
            $.getJSON(SetPricingModel, {s: sessionID, id: priceId, sms_cost:smsCost, response_cost: resCost}, function(res) {
                if(res.error) {
                    miniErrors('div#adminConf', res);
                    return false;
                }

                $('input#smsCost').val('');
                $('input#responseCost').val('');
                $('input#priceId').val('');

                loadSurveyPriceList();
            });
        });

        function loadSurveyPriceList()
        {
            $.getJSON(GetSurveyPricing, { s: sessionID }, function(json) {
                if(json.error) {
                    miniErrors('div#adminConf', json);
                    return false;
                }
                $.each(json.GetSurveyPricing.pricing, function(i, price){
                        var id = price.id;
                        var smsCost = price.sms_cost;
                        var resCost = price.response_cost;
                        var viewUser = 'Yes';
                        if(price.userView == "false")
                        {
                            viewUser = 'No';
                        }
                        var priceList = '<tr id="price_'+id+'">';
                            priceList += '<td>'+smsCost+'</td><td>'+resCost+'</td>';
                            priceList += '<td><a id="view_'+id+'" class="userView">'+viewUser+'</a></td>';
                            priceList += '<td><a id="edit">Edit</a></tr>';
                        
                        $('tr#price_'+id).remove();
                        $('table#priceList').append(priceList);
                        $('tr#price_'+id).data('priceId', id);
                        $('tr#price_'+id).data('smsCost', smsCost);
                        $('tr#price_'+id).data('responseCost', resCost);
                        $('tr#price_'+id).data('userView', price.userView);


                        $('tr#price_'+id+' a#edit').click(function(){
                            var sms = $(this).parent().parent().data('smsCost');
                            var res = $(this).parent().parent().data('responseCost');
                            var pid = $(this).parent().parent().data('priceId');

                            $('input#smsCost').val(sms);
                            $('input#responseCost').val(res);
                            $('input#priceId').val(pid);
                        });

                        $('tr#price_'+id+' a.userView').click(function(){
                            var pid = $(this).parent().parent().data('priceId');
                            $.ajax({
                                type: "POST",
                                url:TogglePricingView,
                                dataType: "jsonp",
                                data: ({price_id:pid, s:sessionID}),
                                success: function(response){
                                    if(response.error)
                                    {
                                        miniErrors('div#listPricing', response);
                                        return false;
                                    }
                                    var view = $('tr#price_'+id).data('userView');
                                    if(view == "true")
                                    {
                                        $("#view_"+pid).html('No');
                                        $('tr#price_'+id).data('userView', false);
                                    }
                                    else
                                    {
                                        $("#view_"+pid).html('Yes');
                                        $('tr#price_'+id).data('userView', true);
                                    }
                                }
                            });
                        });
                });
            });
        }

        //Admin Survey Users list
        $('#adminUsers').click(function(){
            loadAdminSurveyUsers();
            setAdminSelection('adminUsers');
        });

        //Admin Users' Survey Usage
        $('#surveyUsage').click(function () {
            setAdminSelection('surveyUsage');
            loadAdminSurveyUsage();
        });

        //Admin Credits Usage
        $('#creditsUsage').click(function() {
            setAdminSelection('creditsUsage');
            loadAdminCreditsUsage();
        });

        //Admin Users' purchase history
        $('#purchaseHistory').click(function(){
            setAdminSelection('purchaseHistory');
            loadAdminPuchaseHistory();
        });

        //Admin Voucher manage page
        $('#adminVouchers').click(function() {
            setAdminSelection('adminVouchers');
            loadAdminVouchers();
        });

    }
//END ADMIN CONF ------------------------------------------------------------------------------------------------------

//ADMIN SURVEY USERS ------------------------------------------------------------------------------------------------
    function loadAdminSurveyUsers()
    {
        $("#adminConfigs").click(function(){
            $("#adminConfigurations").show();
            $("#adminSurveyUsers").hide();
            $("#adminEditUser").hide();
            $('#adminCreditsUsage').hide();
            $('#adminPurchaseHistory').hide();
            $('#adminVoucherManage').hide();
            setAdminSelection('adminConfigs');
            
        });
        $("#adminConfigurations").hide();
        $("#adminSurveyUsers").show();
        $("#adminEditUser").hide();
        $('#adminSurveyUsage').hide();
        $('#adminCreditsUsage').hide();
        $('#adminPurchaseHistory').hide();
        $('#adminVoucherManage').hide();

        if($("#adminUsers").data('surveyUsersLoaded') != 1)
        {
            $.getJSON(GetSurveyUsers, { s: sessionID }, function(response) {
                if(response.error) {
                    miniErrors('div#adminConf', response);
                    return false;
                }
                var users = response.GetSurveyUsers.users;
                if(users)
                {
                $.each(users, function(i, user){
                    var uid = user.id;
                    var name = user.first_name+' '+user.last_name;
                    var email = user.email;
                    var time = user.addedtime;
                    var gateway = user.sms_gateway;
                    var freeUser = user.free_user;
                    var userHtm = '<tr id="user_'+uid+'"><td>'+name+'</td><td>'+time+'</td><td>'+email+'</td><td>'+gateway+'</td><td>'+freeUser+'</td><td><a id="edit_'+uid+'">Edit</a></td></tr>';
                    $('table#userList tr#user_'+uid).remove();
                    $('table#userList').append(userHtm);
                    $('#edit_'+uid).data('userId', uid);

                    $('table#userList a#edit_'+uid).click(function(){
                        var userId = $(this).data('userId');
                        $("#adminConfigurations").hide();
                        $("#adminSurveyUsers").hide();
                        $('#adminEditUser').show();
                        loadEditSurveyUserDetails(userId);
                    });
                });
                }
            });
            $("#adminUsers").data('surveyUsersLoaded', 1);
        }
    }
    function setAdminSelection(divId)
    {
        $('#adminMenu li a').removeClass("subSlect");
        $('#'+divId).addClass("subSlect");
    }
    function loadEditSurveyUserDetails(userId)
    {
        var formHtm = '<h2>Edit User</h2><form id="editUserSur" method="get"><fieldset>';
            formHtm += '<label for="first_name">First Name</label><input type="text" name="first_name" id="first_name" value="" class="regularfield required" />';
            formHtm += '<label for="last_name">Last Name</label><input type="text" name="last_name" id="last_name" value="" class="regularfield" />';
            formHtm += '<label for="email">Email</label><input type="text" name="email" id="email" value="" class="regularfield required" />';
            formHtm += '<label for="added_time">Added Time</label><input type="text" name="added_time" id="added_time" value="" class="regularfield required" readonly="true" />';
            formHtm += '<label for="user_role_id">Role</label><select id="user_role_id" name="user_role_id"></select>';
            formHtm += '<label for="sms_gateway">SMS Gateway</label><input type="text" name="sms_gateway" id="sms_gateway" value="" class="regularfield" />';
            formHtm += '<label for="free_user">Free USer</label><input type="radio" id="free_user_yes" name="free_user" value="true" />Yes ';
            formHtm += '<input name="free_user" type="radio" id="free_user_no" value="false" checked="true" />No <br />';
            formHtm += '<label for="user_survey_pricing">User Survey Pricing</label><span id="surveyPricing"></span>';
            formHtm += '<input type="submit" value="Update" id="editUser" class="standard_btn small_button"/>';
            formHtm += '<input type="hidden" id="user_id" value="'+userId+'" name="user_id" />';
            formHtm += '<input type="hidden" class="sessionfield" name="s" value="'+sessionID+'">';
            formHtm += '</fieldset></form>';
            
            $('#adminEditUserForm').html(formHtm);
            $.getJSON(GetUserDetails, {s: sessionID, user_id: userId}, function(response) {
                if(response.error) {
                    miniErrors('div#adminEditUserForm', response);
                    return false;
                }
                var user = response.GetUserDetails;
                var firstName = user.first_name;
                var lastName = user.last_name;
                var email = user.email;
                var company = user.company;
                var addedTime = user.added_time;
                var userRoleId = user.user_role_id;
                var smsGateway = user.sms_gateway;
                var freeUser = user.free_user;
                var userPricing = user.survey_pricing_id;
                var userRoles = user.user_roles;
                var surveyPricing = user.survey_pricing;
                
                $('#first_name').val(firstName);
                $('#last_name').val(lastName);
                $('#email').val(email);
                $('#added_time').val(addedTime);
                $('#sms_gateway').val(smsGateway);
                $.each(userRoles, function(i, role){
                    var roleId = role.id;
                    var roleName = role.name;
                    var selected = '';
                     if(userRoleId == roleId) {
                        selected = 'selected="true"'; 
                    }
                    $('select#user_role_id').append('<option value="'+roleId+'" '+selected+'>'+roleName+'</option>');
                });
                
                var priceHtm = '';
                $.each(surveyPricing, function(i, price) {
                    var pid = price.id;
                    var smsCost = price.sms_cost;
                    var resCost = price.response_cost;

                    priceHtm += '<label><input type="radio" name="survey_pricing_id" id="pr_'+pid+'" value="'+pid+'" /> SMS Cost: '+smsCost+', Response Cost: '+resCost+'</label>';
                });
                $('#surveyPricing').html(priceHtm);
                $('#pr_'+userPricing).attr('checked', true);
                if(freeUser == "true")
                {
                    $('#free_user_yes').attr('checked', true);
                }
                //Update function
                updateSurveyUserDetails();
            });
    }
    function updateSurveyUserDetails()
    {
        var userOptions = {
            url: UpdateSurveyUser,
            dataType:  'jsonp',
            success: processSurveyUserUpdate
        }
        function processSurveyUserUpdate(response)
        {
            if(response.error) {
                miniErrors('div#adminEditUserForm', response);
                return false;
            } 
            $("#adminUsers").data('surveyUsersLoaded', 0);
            loadAdminSurveyUsers();
        }
        var l = $('#editUserSur').validate({
                    submitHandler: function(form) {
                        $(form).ajaxSubmit(userOptions);
                    }
            });
    }

//End Amind Survey Users----------------------------------------------------------------------------------------

//ADMIN SURVEY USAGE --------------------------------------------------------------------------------

function loadAdminSurveyUsage()
{
    $("#adminConfigs").click(function(){
        $("#adminConfigurations").show();
        $("#adminSurveyUsers").hide();
        $("#adminEditUser").hide();
        $('#adminSurveyUsage').hide();
        $('#adminCreditsUsage').hide();
        $('#adminPurchaseHistory').hide();
        $('#adminVoucherManage').hide();
    });
    $("#adminConfigurations").hide();
    $("#adminSurveyUsers").hide();
    $("#adminEditUser").hide();
    $('#adminSurveyUsage').show();
    $('#adminCreditsUsage').hide();
    $('#adminPurchaseHistory').hide();
    $('#adminVoucherManage').hide();

    $.getJSON(GetUserSurveyUsage, { s: sessionID }, function(response){
        if(response.error) {
            miniErrors('div#adminSurveyUsage', response);
            return false;
        }
        
        var surveyUsage = response.GetUserSurveyUsage.count;
        var avgUsage = response.GetUserSurveyUsage.average;

        var usageHtm = '<tr><th>Usage Summary</th><th>Average Usage</th></tr><tr><td id="usageSum"><table>';
            usageHtm += '<tr><td>Surveys Created</td><td>:</td><td>'+surveyUsage.surveysCreated+'</td></tr>';
            usageHtm += '<tr><td>Active Surveys</td><td>:</td><td>'+surveyUsage.activeSurveys+'</td></tr>';
            usageHtm += '<tr><td>Survey Users</td><td>:</td><td>'+surveyUsage.surveyUsers+'</td></tr>';
            usageHtm += '<tr><td>Surveys Sent</td><td>:</td><td>'+surveyUsage.surveysSent+'</td></tr>';
            usageHtm += '<tr><td>Survey Responses</td><td>:</td><td>'+surveyUsage.surveyResponses+'</td></tr>';
            usageHtm += '<tr><td>Completed Surveys</td><td>:</td><td>'+surveyUsage.surveysCompleted+'</td></tr>';
            usageHtm += '</table></td><td id="avgUsage">';

        var avgHtm = '<table>';
            avgHtm += '<tr><td>Avg. Survey per User</td><td>:</td><td>'+avgUsage.avgSurveyUser+'</td></tr>';
            avgHtm += '<tr><td>Avg. SMS per Survey</td><td>:</td><td>'+avgUsage.avgSMSSurvey+'</td></tr>';
            avgHtm += '<tr><td>Avg. Response per Survey</td><td>:</td><td>'+avgUsage.avgResponses+'</td></tr>';
            avgHtm += '</table></td></tr>';

        var html = usageHtm + avgHtm;
        $('table#usageTable').html(html);
        $('#backUsageLink').html('<a id="viewUsageDetail">View Detailed Report</a>');
        $('#viewUsageDetail').click(function(){
            loadDetailedSurveyUsage();
        });
    });

    function loadDetailedSurveyUsage()
    {
        $.getJSON(GetDetailedUserSurveyUsage, { s: sessionID }, function(response){
            if(response.error) {
                miniErrors('div#adminSurveyUsage', response);
                return false;
            }

            var users = response.GetDetailedUserSurveyUsage.users;
            var htm = '<tr><th>Name</th><th>SMS Gateway</th><th>Free User</th><th>Surveys</th><th>Active</th><th>SMS</th><th>Responses</th><th>Completed</th></tr><tr>';
            $.each(users, function(i, user){
                var free = 'No';
                if(user.free_user == "true") {
                    free = 'Yes';
                } 
                htm += '<tr><td>'+user.first_name+' '+user.last_name+'</td><td>'+user.sms_gateway+'</td><td>'+free+'</td>';
                htm += '<td>'+user.surveyCreated+'</td><td>'+user.activeSurveys+'</td><td>'+user.surveysSent+'</td><td>'+user.surveysResponse+'</td>';
                htm += '<td>'+user.completedSurveys+'</td></tr>';
            });

            $('table#usageTable').html(htm);
            $('#backUsageLink').html('<a id="viewSurveyUsage">Back to Survey usage</a>');
            $('#viewSurveyUsage').click(function(){
                loadAdminSurveyUsage();
            });
        });
    }
}
//END SURVEY USAGE ---------------------------------------------------------------------------------

//ADMIN USERS CREDITS USAGE ------------------------------------------------------------------

function loadAdminCreditsUsage()
{
    $("#adminConfigs").click(function(){
        $("#adminConfigurations").show();
        $("#adminSurveyUsers").hide();
        $("#adminEditUser").hide();
        $('#adminSurveyUsage').hide();
        $('#adminCreditsUsage').hide();
        $('#adminPurchaseHistory').hide();
        $('#adminVoucherManage').hide();
    });
    $("#adminConfigurations").hide();
    $("#adminSurveyUsers").hide();
    $("#adminEditUser").hide();
    $('#adminSurveyUsage').hide();
    $('#adminCreditsUsage').show();
    $('#adminPurchaseHistory').hide();
    $('#adminVoucherManage').hide();

    $.getJSON(GetUserCreditsUsage, { s: sessionID }, function(response){ 
        if(response.error) {
            miniErrors('div#adminCreditsUsage', response);
            return false;
        }

        var users = response.GetUserCreditsUsage.usage;
        var crdHtm = '<tr><th>Full Name</th><th>SMS Gateway</th><th>Free USer</th><th>Credits Available</th><th>Surveys</th><th>Avg. Usage</th></tr>';
        $.each(users, function(i, user){
            var free = 'No';
            if(user.free_user == "true") { free = 'Yes'; }
            crdHtm += '<tr><td>'+user.first_name+' '+user.last_name+'</td><td>'+user.sms_gateway+'</td><td>'+free+'</td><td>'+user.creditsAvailable+'</td>';
            crdHtm += '<td>'+user.surveysCount+'</td><td>'+user.avgCreditUsage+'</td>';
        });

        $('#creditsUsageList').html(crdHtm);
    });
}
//END

//ADMIN USER BILLING-------------------------------------------------------------------------------------------------
function loadAdminPuchaseHistory()
{
    $("#adminConfigs").click(function(){
        $("#adminConfigurations").show();
        $("#adminSurveyUsers").hide();
        $("#adminEditUser").hide();
        $('#adminSurveyUsage').hide();
        $('#adminCreditsUsage').hide();
        $('#adminPurchaseHistory').hide();
        $('#adminVoucherManage').hide();
    });
    $("#adminConfigurations").hide();
    $("#adminSurveyUsers").hide();
    $("#adminEditUser").hide();
    $('#adminSurveyUsage').hide();
    $('#adminCreditsUsage').hide();
    $('#adminPurchaseHistory').show();
    $('#adminVoucherManage').hide();

    //Date Picker
    $('#start_date').datepicker({ dateFormat: 'yy-mm-dd' }); 
    $("#start_date").datepicker();
    $('#end_date').datepicker({ dateFormat: 'yy-mm-dd' });
    $("#end_date").datepicker();

    $('#billView').click(function() {
        var startDate = '';
            startDate = $('#start_date').val();
        var endDate = '';
            endDate = $('#end_date').val();
        
        $.getJSON(GetPurchaseHistory, { s: sessionID, start_date:startDate, end_date:endDate }, function(response){
            if(response.error) {
                miniErrors('div#adminPurchaseHistory', response);
                return false;
            }

            var payment = response.GetPurchaseHistory.history;
            var htm = '<table id="listingTable" class="tableForm"><tr><th>Name</th><th>Purchase Date</th><th>Amount</th></tr>';
            if(payment)
            {
                $.each(payment, function (i, pay) {
                    htm += '<tr><td>'+pay.first_name+'</td><td>'+pay.date+'</td><td>'+pay.amount+'</td></tr>';
                });
            }
            else
            {
                htm += '<tr><td colspan="3" class="error">No Billing history for this period</td></tr>';
            }
            htm += '</table>';

            $('#listPurchases').html(htm);
        });
    }); 
}
//END PURCHASE HISTORY --------------------------------------------------------------------------------------------------------------

// ADMIN VOUCHERS ---------------------------------------------------------------------------------------------------------------

    function loadAdminVouchers()
    {
        $("#adminConfigurations").hide();
        $("#adminSurveyUsers").hide();
        $("#adminEditUser").hide();
        $('#adminCreditsUsage').hide();
        $('#adminSurveyUsage').hide();
        $('#adminPurchaseHistory').hide(); 
        $('#adminVoucherManage').show();
        $('#voucherUserSession').val(sessionID);
        
        //Hide Create option
        $('#adminCreateVoucher').hide();
        $('#voucher_expiry').datepicker({ dateFormat: 'yy-mm-dd' });
        $("#voucher_expiry").datepicker();
        
        function loadVouchersList()
        {
            $.getJSON(GetVouchers, {s: sessionID}, function(response){
                var vouchers = response.GetVouchers.vouchers;
                var vhtm = '';
                if(vouchers)
                {
                    $.each(vouchers, function (i, voucher){
                        vhtm = '<tr id="voucher_'+voucher.id+'"><td>'+voucher.code+'</td><td>'+voucher.credits+'</td><td>'+voucher.expiry_date+'</td>';
                        vhtm += '<td>'+voucher.redeem+'</td><td><a class="edit">Edit</td><td><a class="delete">Delete</a></td></tr>';
                        $('#voucher_'+voucher.id).remove();
                        $('#vouchersTable').append(vhtm);
                        $('#voucher_'+voucher.id).data('voucherId', voucher.id);

                        //Edit
                        $('tr#voucher_'+voucher.id+' a.edit').click(function(){                            
                            var vid = $(this).parent().parent().data('voucherId');
                            loadVoucherDetails(vid);
                        });
                        //Delete
                        $('tr#voucher_'+voucher.id+' a.delete').click(function(){
                            var vid = $(this).parent().parent().data('voucherId');
                            deleteVoucher(vid);
                        });
                    });
                }
                else
                {
                    vhtm += '<tr><td colspan="6" class="error">No Vouchers</td></tr>';
                }
            });
        }
       
        $('#createVoucher').click(function(){
            $('#adminCreateVoucher').show("slow");
            $('#voucher_id').val('');
            $('#old_voucher_id').val('');
            $('#voucher_code').val('');
            $('#voucher_credits').val('');
            $('#voucher_expiry').val('');
            $('#voucher_redeem').val('');
            $('#btnCreateVoucher').val('Create');
        });

        function loadVoucherDetails(voucherId)
        {
            $.getJSON(GetVoucherDetails, {s: sessionID, voucher_id: voucherId}, function(response){
                var voucherId = response.GetVoucherDetails.voucher.id;
                var voucherCode = response.GetVoucherDetails.voucher.code;
                var voucherCredits = response.GetVoucherDetails.voucher.credits;
                var voucherExpiry = response.GetVoucherDetails.voucher.expiry_date;
                var voucherRedeem = response.GetVoucherDetails.voucher.redeem;
                
                $('#voucher_code').val(voucherCode);
                $('#voucher_credits').val(voucherCredits);
                $('#voucher_expiry').val(voucherExpiry);
                $('#voucher_redeem').val(voucherRedeem);
                $('#old_voucher_id').val(voucherCode);
                $('#voucher_id').val(voucherId);
                $('#btnCreateVoucher').val('Update');
                $('#adminCreateVoucher').show("slow");
            });    
        }

        $('#btnCreateVoucher').click(function(){
            var btnVal = $('#btnCreateVoucher').val();
            var handlerURL = '';
            if(btnVal == 'Create')
            {
                handlerURL = CreateVoucher
            }
            else
            {
                handlerURL = UpdateVoucher;
            }
            var ajaxOpt = {
                url: handlerURL,
                dataType:  'json',
                type: "POST",
                success: function(response) {
                    if(response.error) {
                        miniErrors('div#adminCreateVoucher', response)
                        return false;
                    }
                    $('#adminCreateVoucher').hide();
                    //Update Voucher list
                    loadVouchersList();

                }
            }
            $('#frmCreateVoucher').validate({
                submitHandler: function(form) {
                    $(form).ajaxSubmit(ajaxOpt);
                }
            });
        });

        function deleteVoucher(voucherId)
        {
            $.getJSON(DeleteVoucher, {s: sessionID, voucher_id: voucherId}, function(response){
                $('#voucher_'+voucherId).remove();                
            });
        }
        loadVouchersList();
    }
//END ADMIN VOUCHERS ----------------------------------------------------------------------------------------

    function setUserCreditsLeft(spanId)
    {
        $.getJSON(GetCreditBalance, { s: sessionID }, function(response) {
            if(response.error) {
                miniErrors('div#Home', response);
                return false;
            }

            var credits = response.GetCreditBalance.credits;
            $('#'+spanId).html(credits);
        });
    }
// REPORTS -------------------------------------------------------------------------------------------------------------------
    function loadUserReports()
    {
        $('#menuUserPurchases').click(function(){
            $('#startdate').val('');
            $('#enddate').val('');
            $('#purchasesView').click();
            setselection('menuUserPurchases');
        });

        //Date Picker
        $('#startdate').datepicker({ dateFormat: 'yy-mm-dd' });
        $("#startdate").datepicker();
        $('#enddate').datepicker({ dateFormat: 'yy-mm-dd' });
        $("#enddate").datepicker();

        $('#purchasesView').click(function(){
            viewUserCreditsPurchases();
        });
        
        $('#menuSurveysSent').click(function(){
            $('#distSurveys').html('<option value="">Select a survey</option>');
            $('#sentSMSListing').html('');
            setselection('menuSurveysSent');
            loadSurveysSendStatus();
        });

        $('#menuUserUsage').click(function(){
            setselection('menuUserUsage');
            loadUserCreditsUsage();
        });
        $('#menuSurveyReport').click(function(){
            setselection('menuSurveyReport');
            loadUserSurveyReport();
        });
        viewUserCreditsPurchases();
        setselection('menuUserPurchases');
        
    }
    function setselection(divId)
    {
        $('#reportsMenu li a').removeClass("subSlect");
        $('#'+divId).addClass("subSlect");
    }
    function viewUserCreditsPurchases()
    {
        $('#userPurchaseHistory').show();
        $('#userCreditsUsage').hide();
        $('#userSurveysStatus').hide();
        $('#userSurveyReport').hide();
        var startDate = '';
        var endDate = '';
        startDate = $('#startdate').val();
        endDate = $('#enddate').val();

        $.getJSON(GetUserPurchaseHistory, {s: sessionID, start_date:startDate, end_date:endDate}, function(response){
            if(response.error) {
                miniErrors('div#userPurchaseHistory', response);
                return false;
            }
        
            //Setting date fields
            $('#startdate').val(response.GetUserPurchaseHistory.start_date);
            $('#enddate').val(response.GetUserPurchaseHistory.end_date);

            var purchases = response.GetUserPurchaseHistory.history;
            var htm = '<table id="listingTable" class="tableForm"><tr><th>Purchase Date</th><th>Credits</th><th>Amount</th><th>Payment</tr>';
            if(purchases)
            {
                $.each(purchases, function (i, purchase) {
                    htm += '<tr><td>'+purchase.date+'</td><td>'+purchase.credits_purchased+'</td><td>'+purchase.amount+'</td><td>'+purchase.payment_option+'</td></tr>';
                });
            }
            else
            {
                htm += '<tr><td colspan="3" class="error">No purchases for this period</td></tr>';
            }
            htm += '</table>';

            $('#creditsPurchaseLists').html(htm);
        });        
    }
    
    function loadSurveysSendStatus()
    {
        $('#userPurchaseHistory').hide();
        $('#userSurveysStatus').show();
        $('#userCreditsUsage').hide();
        $('#userSurveyReport').hide();

        //Get Distributed Surveys
        $.getJSON(GetDistributedSurveys, {s: sessionID}, function(response){
            var surveys = response.GetDistributedSurveys.surveys;
            if(surveys)
            {
                $.each(surveys, function(i, survey){
                    var title = survey.title;
                    var ref = survey.reference;
                    title = ref+' - '+title;
                    if(title.length > 40)
                    {
                        title = title.substr(0, 40)+'...';
                    }
                    $('#distSurveys').append('<option value="'+survey.id+'">'+title+'</option>');
                });                
            }
        });

        $('#distSurveys').change(function(){
            var surveyId = $('#distSurveys').val();
            if(surveyId)
            {
                viewSurveySendStatus(surveyId);
            }
            else
            {
                $('#sentSMSListing').html('');
            }
        });
    }
    function viewSurveySendStatus(surveyId)
    {
        $.getJSON(GetSurveysSentStatus, {s: sessionID, survey_id: surveyId}, function(response){
            var surveyStatus = response.GetSurveysSentStatus.status;
            var smsSent = response.GetSurveysSentStatus.SMS;
            var userRate = response.GetSurveysSentStatus.rates;
            if(smsSent)
            {
                var htm = '<table id="listingTable" class="tableForm"><tr><th>Origination Time</th><th>Destination</th><th>Credit Used</th><th>Status</th></tr>';
                var delStatus = '';
                $.each(smsSent, function(i, message){
                    if(message.message_delivered == "false") {
                        delStatus = 'Pending';
                    }
                    else
                    {
                        delStatus = 'Delivered';
                    }
                    htm += '<tr><td>'+message.time+'</td><td>'+message.msid+'</td><td>'+userRate.sms_cost+'</td><td>'+delStatus+'</td></tr>';
                });
                $('#sentSMSListing').html(htm);
            }
            else
            {
                $('#sentSMSListing').html('');
            }
        }); 
    }
    function loadUserCreditsUsage()
    {
        $('#userPurchaseHistory').hide();
        $('#userSurveysStatus').hide();
        $('#userCreditsUsage').show();
        $('#userSurveyReport').hide();

        $.getJSON(GetCreditUsage, {s: sessionID}, function(response){
            var summary = response.GetCreditUsage.usage;
            var htm = '<tr><th colspan="3">Summary</th></tr>';
                htm += '<tr><td>Credits Available</td><td>:</td><td>'+summary.creditsAvailable+'</td></tr>';
                htm += '<tr><td>Credits Used</td><td>:</td><td>'+summary.creditsUsed+'</td></tr>';
                htm += '<tr><td>Total Credits</td><td>:</td><td>'+summary.totalCredits+'</td></tr>';
                htm += '<tr><td>Surveys Sent</td><td>:</td><td>'+summary.distributedSurveys+'</td></tr>';
                htm += '<tr><td>Surveys Created</td><td>:</td><td>'+summary.surveysCount+'</td></tr>';
                htm += '<tr><td>Average Usage</td><td>:</td><td>'+summary.avgCreditUsage+'</td></tr>';

                $('#userCreditsSummary').html(htm);
        });
    }
    function loadUserSurveyReport()
    {
        $('#userPurchaseHistory').hide();
        $('#userSurveysStatus').hide();
        $('#userCreditsUsage').hide();
        $('#userSurveyReport').show();

        $.getJSON(GetDistributedSurveys, {s: sessionID}, function(response){
            var surveys = response.GetDistributedSurveys.surveys;
            if(surveys)
            {
                $('#userSurveyList').html('');
                $('#userSurveyList').append('<thead><th>Id</th><th>Title</th><th>Responses</th><th>Deployed Date</th><th>&nbsp;</th><th>&nbsp;</th></thead>'); 
                $.each(surveys, function(i, survey){
                    var titleShort = survey.title;
                    if(titleShort.length > 40)
                    {
                        titleShort = titleShort.substr(0, 40)+'...';
                    }
                    var htm = '<tr id="rview_'+survey.id+'">';
                        htm += '<td>'+survey.reference+'</td>';
                        htm += '<td>'+titleShort+'</td>';
                        htm += '<td>'+survey.responses+'</td>';
                        htm += '<td>'+survey.deployed_date+'</td>';
                        htm += '<td><a id="viewRep">View report</a></td>';
                        htm += '<td><a id="csvExport">Export CSV</a></td>';
                        htm += '</tr>';
                    $('#userSurveyList').append(htm);

                    $('tr#rview_'+survey.id).data('surveyid', survey.id);
                    $('tr#rview_'+survey.id).data('surevytitle', survey.title);
                });

                $('a#viewRep').click(function(){
                    var sid = $(this).parent().parent().data('surveyid');
                    var stitle = $(this).parent().parent().data('surevytitle');
                    $('#userSurveyReport .screentitle').empty().append('<span class="backtohome linkstyling">Deployed Surveys</span> > '+stitle);
                    $('span.backtohome').click(function(){
                        $('div#reporting').hide();

                        $('#userSurveyList').show();
                        $('#userSurveyReport .screentitle').empty().append('Deployed Surveys');
                    });
                    $('#userSurveyList').hide();
                    $('#userSurveyReport').css("width", "940px");
                    $('#userSurveyReport').css("float", "left");
                    $('div#reporting').show();
                    $('div#reporting').html('<div id="report_left_col"></div><div id="report_right_col"></div><div class="clearer"></div>');
                    getSurveyReportData(sid);
                });
                $('a#csvExport').click(function(){
                    var sid = $(this).parent().parent().data('surveyid');
                    window.frames['exportCsvFrame'].location = ExportCsv+'&s='+sessionID+'&sid='+sid;
                });
            }
            else
            {
                $('#userSurveyList').html('<div class="error">No Deployed Surveys</div>'); 
            }
            $('#menuSurveyReport').click(function(){
                $('#userSurveyList').show();
                $('div#reporting').hide();
            });
        });
    }
    //END REPORTS ----------------------------------------------------------------------------------------------------------------
    function loadHelp()
    {
        $('#contactUs').hide();
        $('#helpContact').click(function(){
            $('#faqs').hide();
            $('#contactUs').show();
            $('#sessionId').val(sessionID); 
            
            $.getJSON(GetUserData, {s: sessionID}, function(response){
                var userEmail = response.GetUserData.email;
                var userName = response.GetUserData.first_name+' '+response.GetUserData.last_name;
                $('#name').val(userName);
                $('#email').val(userEmail);
            });            

            $('#contactBtn').click(function(){
                $('#contactUsFrm').validate({
                    submitHandler: function(form) {
                        $(form).ajaxSubmit({
                            url: ContactUs,
                            dataType:  'jsonp',
                            success: function(response) {
                                if(response.error)
                                {
                                    miniErrors('div#contactUs', response);
                                    return false;
                                }
                                $('#comment').val('');
                                $('div#contactUs').block({css: {color: '#25c058'},message:"Thank you! If you have requested a reply, a Locatrix staff member will contact you shortly."+olclicktocontinue});
                            }
                        });
                    }  
                });
            });

            $('#helpCancel').click(function(){
                $('#contactUs').hide();
                $('#faqs').show();
            });
        });
    }
    //Load API setup
    function loadAPISetup()
    {
        $('.sessionfield').val(sessionID);
        $('#frm_keys').validate({         
            submitHandler: function(form) {
                $(form).ajaxSubmit({
                    url: GenerateAuthKey,
                    dataType: "jsonp",
                    type: "POST",
                    success: function(res) {
                        if(res.error)
                        {
                            miniErrors('#applicationkeys', res.error);
                            return false;
                        }
                        $('#application_url').val('');
                        $('#application_name').val('');
                        $('#post_result_url').val('');
                        getApplicationKeys();
                    }
                });
            }
        });

        function getApplicationKeys()
        {
            $.getJSON(GetUserApplicationKeys, { s: sessionID }, function(res) {
                var keys = res.GetUserApplicationKeys.keys;
                if(keys)
                {
                    $('#listAppKeys div.error').remove();
                    $('#appKeysList').show();
                    $('#appKeysList').html('<tr><th>Appication Name</th><th>Application Key</th><th>&nbsp;</th><th>&nbsp;</th></tr>');
                    $.each(keys, function(i, keys) {
                        var id = keys.id;
                        var key = keys.key;
                        var name = keys.application_name;                   
                        $('#appKeysList').append('<tr id="key'+id+'"><td>'+name+'</td><td>'+key+'</td><td><a class="editKeys">edit</a> <a class="deleteKeys">delete</a></td></tr>');
                        $('#key'+id).data('key', key);
                    });

                    $('.editKeys').click(function(){
                        var trId = $(this).parent().parent().attr("id");
                        var appKey = $('#'+trId).data('key');
                        $.getJSON(GetKeyData, { s: sessionID, key: appKey }, function(res){
                            var appurl = res.GetKeyData.appUrl;
                            var appname = res.GetKeyData.appName;
                            var posturl = res.GetKeyData.postUrl;

                            $('#application_url').val(appurl);
                            $('#application_name').val(appname);
                            $('#post_result_url').val(posturl);
                        });                        
                    });
                    $('.deleteKeys').click(function(){
                        var trId = $(this).parent().parent().attr("id");
                        var appKey = $('#'+trId).data('key');
                        $.getJSON(DeleteApplicationKey, {s: sessionID, key: appKey}, function(res){
                            if(res.error)    
                            {
                                miniErrors('#applicationkeys', res.error);
                                return false;
                            }
                            $('#'+trId).remove();
                            if($('#appKeysList tr').length <= 1)
                            {   
                                $('#appKeysList').html('<tr><td class="error">No Application Keys</td></tr>');
                            }
                        });    
                    });
                }
                else
                {
                    $('#listAppKeys').append('<div class="error">No Application Keys</div>');
                }
            });
        }
        $.getJSON(GetConfigValues, {s: sessionID}, function(json) {
            if(json.error)
            {
                return false;
            }
            var apiurl = json.GetConfigValues.config.apihost;
            apiurl = apiurl+'/SendSurvey/REST/'
            $('#apiRestUrl').html(apiurl);
        });
        getApplicationKeys();
    }
});


