/// <reference path="jquery-1.3.2.js" />
/// <reference path="jquery-ui-1.7.2.js" />
/// <reference path="jquery-cookie.js" />

/*
General javascript functions for use throughout.
Daishik Chauhan - 5/6/08
*/

function clearEmailInputField(field)
{
	var matchValues = new Array(1);
	matchValues[0] = 'enter email address';
	
	for(var i=0; i<matchValues.length; i++)
	{
		if(field.value==matchValues[i])
		{
			field.value='';
			break;
		}
	}
}

/****************************************************************
**			New scripts to load jQuery and UI				*****
***         Daishik Chauhan Oct 2009                        *****
****************************************************************/
var MaxDownloadFormLoadAttempts = 4;
var FormLoadAttempts = 1;
var FormTimeout;
var CookieName = 'DownloadQuestionnaire';

//This function recurses to maximise the probability that the scripts are initialised 
function DoDownload(file, func)
{
	if(func!=null) func();  //execute the other functions
	clearTimeout(FormTimeout);
	var scriptsInitialised = JQueryScriptInit();		
	if(scriptsInitialised)
	{
		//alert(FormLoadAttempts);
		//initialise the dialog if not already
		InitDialog(file);
		//show the form - we need to loop this because of synchronisation issues to ensure the dialog opens
		var interval = setInterval(function() {
		    if ($('#dialogPanel').dialog('isOpen'))
		        clearInterval(interval);
		    else {
		        if (!QuestionnaireAlreadyAsked(CookieName))
		        {
		        	//update the fields in the form
					var basefilename = file.split('\/')[file.split('\/').length - 1];
					$('#filenamespan').text(basefilename);
		            $('#dialogPanel').dialog('open');
		        }
		        else {
		            clearInterval(interval);
		            CloseAndContinue(file, null);
		        }
		    }
		}, 1);
	}
	else
	{
		if(FormLoadAttempts<=MaxDownloadFormLoadAttempts)
		{
			FormTimeout = setTimeout(function() {	DoDownload(file); }, 250);
		}
		else
			CloseAndContinue(file,null);
	}
	return false;  //prevent the href of the download link from running
}

function JQueryScriptInit()
{
	//initialise jQuery
	if(JQueryInit())
	{
		//we have jQuery!
		//alert($('#accessHelp').text());
		//use jQuery to get the ui file
		if(JQueryUIInit()) {
		    JQueryCookie();		
			JQueryUICss();
			return true;
		}
		else
			return false;
		
	}
	else
		return false;
}


function JQueryInit()
{
	if(!self.jQuery)
	{
		var head = document.getElementsByTagName("head")[0];

		//get the script
		var scriptitem = document.createElement("script");
		scriptitem.id = "jquery";
		scriptitem.src = "/htaweb/scripts/jquery-1.3.2.js";
		scriptitem.type = "text/javascript";
		head.appendChild(scriptitem);
	
		var maxcheckattempts = 100;
		var checks = 1;
		var jqueryloaded = true;
		while (!self.jQuery)
		{
			if(checks>maxcheckattempts)
			{
				jqueryloaded = false;
				//alert('Timed out');
				break;
			}		
			setTimeout(function(){}, 100);
			checks++;
		}
		return jqueryloaded;
	}
	else
	{
		//alert('jQuery already loaded');
		return true;
	}
}


function JQueryUIInit()
{
	if(!$.ui)
	{
		var uiscript = '<script language="javascript" type="text/javascript" id="jqueryui" src="/htaweb/scripts/jquery-ui-1.7.2.js" />';
		$('head').append(uiscript);
	
		var maxcheckattempts = 100;
		var checks = 1;
		var jqueryloaded = true;
		while (!$.ui)
		{
			if(checks>maxcheckattempts)
			{
				jqueryloaded = false;
				//alert('jQuery UI load timed out');
				break;
			}		
			setTimeout(function(){}, 100);
			checks++;
		}
		return jqueryloaded;
	}
	else
	{
		//alert('jQuery UI already loaded');
		return true;
	}
}


function JQueryUICss()
{
	if($('#jqueryuicss').length==0)
	{
		$('head').append('<link id="jqueryuicss" rel="stylesheet" type="text/css" media="screen" href="/htaweb/css/jquery-ui-1.7.2.css" />');
		//alert('css loaded');
	}
	//else
	//	alert('css already loaded');
}

function JQueryCookie() {
    if (!$.cookie) {
        var cookiescript = '<script language="javascript" type="text/javascript" id="jquerycookies" src="/htaweb/scripts/jquery-cookies.js" />';
        $('head').append(cookiescript);
    }
}

function InitDialog(file)
{
	if( $('#dialogPanel').dialog().length==0 ) 
	{
		//a short loop here to ensure the div is now in the DOM
		var interval = setInterval(function()
		{
			//create a form container
			if($('#dialogPanel').length==0)
				$('#wrapper').append('<DIV style="DISPLAY:block;" id="dialogPanel"></DIV>');
			if($('#dialogPanel').length>0) 
			{
				if($('#dialogPanel').html().length==0)
				{
					//get the form html
					$('#dialogPanel').load('/htaweb/forms/downloadform.htm', null, function() { 
					    //LoadEthnicities();
						InitDialogPopup(file); 
					});
				}
				else
					InitDialogPopup(file);
				clearInterval(interval); 
			}
		}, 1);
	}
}

function InitDialogPopup(file)
{
    $('#dialogPanel').dialog({
        autoOpen: false,
        title: 'User Survey',
        width: 450,
        buttons: {
            "Skip": function() { CloseAndContinue(file, true); },
            "OK": function() { CloseAndContinue(file, false); }
        }
    });
}

//set cookie to expire in distant future
function SetCookie(name, userid, file, hasSkipped, downloads) {
	var cookieval = "UserId:" + userid + ",LastDownload:" + file + ",FormSkipped:" + hasSkipped + ",Downloads:" + downloads;
    $.cookie(name, cookieval, { expires: 999, path: '/' });
}

function ReadCookie(name) {
    return ($.cookie(name)==null) ? "" : $.cookie(name);
}

function GetCookieProperty(name, property) {
    var cookieval = ReadCookie(name);
    var retval = '';
    $.each(cookieval.split(','), function(i, val) {
        if ($.trim(val.split(':')[0]).toLowerCase() == property.toLowerCase()) {
            retval = $.trim(val.split(':')[1]);
            return false;
        }
    });
    if(property.toLowerCase() == 'downloads')
    {
		if(retval.length==0) return 0;
		else return parseInt(retval);
	}
	else
		return retval;
}

function UpdateCookie(name, userid, file, hasSkipped) {
    SetCookie(name, userid, file, hasSkipped, GetCookieProperty(name,'Downloads')+1);
}

//return true is popup has already appeared and been accepted or rejected.
function QuestionnaireAlreadyAsked(name) {
    var cookieval = ReadCookie(name);
    if (cookieval == null)
        return false;
    //cookie presence test
    if (cookieval.length>0)
        return true;
    else
        return false;
}

function CloseAndContinue(file, hasSkipped)
{
	if ($('#dialogPanel').dialog('isOpen')) $('#dialogPanel').dialog('close');
	//Consider how many ways there are of closing this and ensure that a cookie indicating skip is always created - and the db updated.

    if (hasSkipped == null) hasSkipped = GetCookieProperty(CookieName,'FormSkipped');
    ProcessForm(file, hasSkipped);
}

function ProcessForm(file, hasSkipped) {
	//call made to service
	//userId, ageRange, gender, ethnicity, file, leafletFor, postcode, formSkipped
	var userid = GetCookieProperty(CookieName, 'UserId'); //may be empty if new cookie
	//get the other values
	var dlFor = ($('#leafletFor').length>0) ? $('#leafletFor').val() : 'Unknown';
	var pcode = ($('#postcode').length>0) ? $('#postcode').val() : 'Unknown';
	var ethnicity = 'Unknown';
	var ageGroup = ($('#ageGroup').length>0) ? $('#ageGroup').val() : 'Unknown';
	var gender = ($('#gender').length>0) ? $('#gender').val() : 'Unknown';
	
	var wsUrl = '/DownloadRecordsManager/RecordDownloads.asmx/RecordDownload';
    $.ajax({
		type: "POST",
		url: wsUrl,
		cache : false,
		data: {
			userid:userid,
			agerange:ageGroup,
			gender:gender,
			ethnicity:ethnicity,
			dlfile:file,
			dlfor:dlFor,
			postcode:pcode,
			skipped:hasSkipped },
		dataType : 'xml',
		success: function(msg, status){
			var uid = $.browser.msie ? msg.text : $(msg).text();
			//alert( "Data Saved: " +  uid);
			UpdateCookie(CookieName, uid, file, hasSkipped);	
		},
		error: function(xhr, status, err){
			alert('Status: ' + xhr.status + ': ' + xhr.statusText);
		},
		complete: function(){
			//alert('Redirecting now...');
			location.href = file;
		}
		
	});

}

function LoadEthnicities() {
    var ethDropList = $("#ethnicity");
    var arrEthnicities = new Array('White English', 'White Scottish', 'White Welsh', 'White British', 'White Northern Irish', 'Gypsy or Traveller', 'Indian', 'Pakistani', 'Bangladeshi', 'Chinese', 'Asian British', 'Asian English', 'Asian Scottish', 'Asian Welsh', 'Any other Asian background', 'African', 'Black British', 'Black English', 'Black Scottish', 'Black Welsh', 'Caribbean', 'Any other black background', 'Mixed: White and Black Caribbean', 'Mixed: White and Black African', 'Mixed: White and Asian', 'Other mixed/multiple background', 'Arab', 'Other');
    arrEthnicities = $(arrEthnicities).sort();
    $.each(arrEthnicities, function(i, val) {
        ethDropList.append('<option value="' + val + '">' + val + '</option>');
    });
}
/****************************************************************
**			End scripts to load jQuery and UI				*****
****************************************************************/