// JavaScript Document


$(document).ready(function(){
    $("#logo").pngFix();
    $("#nav").pngFix();
    $("#header").pngFix();
    $("#menu").pngFix();
    $("#question").pngFix();
    $("#reviewquestion").pngFix();
    $("#footer-area").pngFix();
    //fontSizer();

	$("a#returnToMenu").click(function(){
		save('/course.php',true);
		return false;
	});

	// This is to make sure data is saved when the user clicks on the 'read more' links etc.
	$('a[class!="noSave"]').click(function(){
		if(typeof save == 'function')
		{			
			save(this.href,true);
			return false;
		}
		else
		{
			return true;
		}
	});	
});

function openPage(url)
{
	window.open(url);
}

var dialog = $("#savecheck")[0];

function doSignup() {

	if ($("input[name=privacy]:checked").val() == '1' && isValidEmail($("#email").val()) === true) 
	{
		document.signup.submit();
	}
	else
	{	
		$("#login-msg").remove();
		$("#login-msg-email").remove();

		if (isValidEmail($("#email").val()) === false)
		{
			$("#loginfooter").prepend('<div class="login-msg-email" id="login-msg-email">You have entered an invalid email address.</div>');
		}
		
		if ($("input[name=privacy]:checked").val() != '1')
		{
			$("#loginfooter").prepend('<div class="login-msg" id="login-msg">You must accept the terms and conditions.</div>');
		}

		if ($("input[name=name]").val() == '')
		{
			$("#loginfooter").prepend('<div class="login-msg" id="login-msg">You must enter your name.</div>');
		}
	}
	
	return false;
}

function isValidEmail(str) {
	apos = str.indexOf("@");
	dotpos = str.lastIndexOf(".");
	if (apos < 1 || dotpos-apos < 2) {
		return false;
	} else {
		return true;
	}
}

function toggleMenu(id) {

	// check for Internet Explorer
	ie = 0;
	if (navigator.appVersion.indexOf("MSIE")!=-1){
		temp=navigator.appVersion.split("MSIE")
		version=parseFloat(temp[1]);
		ie = 1;
	}

	if ($("#panel-" + id).css('display') == 'none') {
		if (ie != 1) {
			$("#panel-" + id).slideDown("slow");
		} else {
			$("#panel-" + id).show();
		}
		$("#arrow-" + id).attr("src","/images/arrow_south.gif");
	} else {
		if (ie != 1) {
			$("#panel-" + id).slideUp("slow");
		} else {
			$("#panel-" + id).hide();
		}
		$("#arrow-" + id).attr("src","/images/arrow_east.gif");
	}
}

function updateSliderLabel(labels, value, label) {
	var val = Math.round((100 / value));

	var span = '<span style="font-size:12px; color: #000000;">You have selected : </span>';

	if (value == 0) {
		$("#slider-current-"+label).html(span + labels[(labels.length-1)]);
	} else {
		$("#slider-current-"+label).html(span + labels[(val-1)]);
	}
}

function toggleArea(area)
{
	if ($("#" + area).css('display') == 'none')$("#"+area).show();
	else $("#" + area).hide();
}

function toggleOther(other, id) {
	if ($("#"+id+" :selected").attr("value") == "Other tourism business") {
		$("#"+other).show();
	} else {
		$("#"+other).hide();
	}
}

function toggleOthers(other, id) {
	if ($("#"+id+" :selected").attr("value") == "Other tourism business") {
		$("#"+other).css("visibility","");
	} else {
		$("#"+other).css("visibility","hidden");
	}
}

function toggleVisitor(id) {

	$("#family").hide();
	$("#older").hide();
	$("#group").hide();

	switch ($("#"+id+" :selected").attr("value")) {
	case "Family":
		$("#family").show();
		break;
	case "Older couple with mobility difficulties":
		$("#older").show();
		break;
	case "Group of friends, one wheelchair user":
		$("#group").show();
		break;
	}
}

function toggleProvider(id) {

	$("#accommodation").hide();
	$("#attraction").hide();

	switch ($("#"+id+" :selected").attr("value")) {
	case "Accommodation":
		$("#accommodation").show();
		break;
	case "Attraction":
		$("#attraction").show();
		break;
	case "Other":
		save('/three/destination_team_attitude.php',true);
		break;
	}
}

function serialize(id, strip, rep) {
    serialData = [];

    var submitData = '';
    list = $('#'+ id + " li");

	if (strip != "") {
		id = id.replace(strip,"");
	}

    for (var count = 0; count < (list.length); count++) {
            var thisElementId = list[count].getAttribute('id');

			if (rep != "") {
				thisElementId = thisElementId.replace(/_/g," ");
			}

             submitData += id + '[]=' + thisElementId + '&';
    }

    return submitData;
};
function serializeString(id, alpha) {
    serialData = '';

    var submitData = '';
    list = $('#'+ id + " li");

	if (alpha) {
		var newlist = new Array();

		for (var count = 0; count < (list.length); count++) {
			var thisElementId = list[count].getAttribute('id');
			 newlist[count] = thisElementId;
		}

		newlist.sort();

		return newlist.join('');
	} else {
		for (var count = 0; count < (list.length); count++) {
			var thisElementId = list[count].getAttribute('id');
			submitData += thisElementId;
		}
		return submitData;
	}
};

function spinner() {
	$("#spinner").pause(3000).fadeOut('slow');
}

function addKeyword(area) {

	var word = $("#new_action").val();

	if (word != "") {

		var id = word.replace(/ /g,'_');

		if (area) {
			$('#'+area).append('<li id="'+id+'" class="keywordItem">'+word+'</li>');
			$('#'+area).sortable("refresh");
		}

		$("#new_action").val('');

	}

}

function redirection(url,target) {
	if (url)
	{
		// Hack - some pages end up passing true as the 2nd param to override to dialogue blocker but end up here, opening a new window
		if (target && (target!=true || target!=1))
		{
			window.open(url,target);
		}
		else
		{
			window.location=url;
		}
	}
}

function showPriority(flag) {

	var top = $("#"+flag+"_img").position().top + 33; // get the top position of the image + image height
	var left = $("#"+flag+"_img").position().left - 2; // get the left position of the image - border width

	ie = 0;
	if (navigator.appVersion.indexOf("MSIE")!=-1){
		temp=navigator.appVersion.split("MSIE")
		version=parseFloat(temp[1]);
		ie = 1;
	}

	if (ie != 1) {
		var msg = '';
	} else {
		var msg = '<p>&nbsp;</p>';
		msg += '<p><span class="label">&nbsp;</label></p>';
	}

	msg += '<p onclick="setPriority(\''+flag+'\',2);"><img src="/images/priority/flag-2.gif" alt="High Priority"> <span class="label">High Priority</label></p>';
	msg += '<p onclick="setPriority(\''+flag+'\',1);"><img src="/images/priority/flag-1.gif" alt="Medium Priority"> <span class="label">Medium Priority</label></p>';
	msg += '<p onclick="setPriority(\''+flag+'\',0);"><img src="/images/priority/flag-0.gif" alt="Low Priority"> <span class="label">Low Priority</label></p>';

	$("#priority-panel").html(msg);
	$("#priority-panel p").hover(function () { $(this).css("background-color","#CCCCCC"); }, function () { $(this).css('background-color','#FFFFFF'); } );
	$("#priority-panel").css('position','absolute').css('left',left+'px').css('top',top+'px').show();

}

function setPriority(flag, priority) {
	$("#priority-panel").hide();
	$("#"+flag+"_priority").attr('value',priority);
	$("#"+flag+"_img").attr('src','/images/priority/flag-'+priority+".gif");
}

function addPlan(plan) {

	// count child elements in table
	var tbl = plan + '_table';
	var val = $("#"+plan+"_add").val();
	var next = document.getElementById(tbl).rows.length;

	var data = '<tr> <td class="tdplan"><input type="text" class="plan" name="'+plan+'_plan'+next+'_plan" id="'+plan+'_plan'+next+'_plan" value="'+val+'" size="50" /></td> <td class="tdcost"><input type="text" class="cost" name="'+plan+'_plan'+next+'_cost" id="'+plan+'_plan'+next+'_cost" value="" size="10" /></td> <td class="tdwhom"><input type="text" class="whom" name="'+plan+'_plan'+next+'_whom" id="'+plan+'_plan'+next+'_whom" value="" /></td> <td class="tdpri"><input type="text" name="'+plan+'_plan'+next+'_priority" id="'+plan+'_plan'+next+'_priority" value="0" style="display:none;" /> <div class="priority-widget"> <div class="flag"><img src="/images/priority/flag-0.gif" alt="Priority" id="'+plan+'_plan'+next+'_img"></div> <div class="handle"><img src="/images/priority/handle.gif" alt="Set Priority" onclick="showPriority(\''+plan+'_plan'+next+'\');"></div> </div> </td> </tr>';

	if (val) {
		$("#"+tbl).append(data);

	}
}

function addColleague() {

	// count child elements in table
	var tbl = 'colleague_table';
	var email = $("#email").val();

	if (isValidEmail(email)===true) {
		var next = document.getElementById(tbl).rows.length;

		if (next == 1) {
			$("#"+tbl).show();
		}

		var data = '<tr><td><input type="text" name="colleague_'+next+'_email" size="25" value="'+email+'" /></td></tr>';

		if (email) {

			$("#"+tbl).append(data);
			$("#email").val('');
		}
	} else {
		return false;
	}
}

function generateUser() {

	var name = $("#name").val();

	name = name.replace(' ','');
	name = name.toLowerCase();
	name += getRandomNum();
	name += getRandomNum();

	if ($("#username").val() == "Edit username if required" || $("#username").val() == name) {
		$("#username").val(name);
	}


}

function emailInvitations(user) {
	document.invitations.send_email.value = '1';

	var data = '';
	var tbl = 'colleague_table';

	if (document.getElementById(tbl).rows.length > 1) {
		var allInputs = $(":input");
		for (var i=0; i<allInputs.length; i++) {
			data += $(allInputs[i]).attr("name") + "=" + $(allInputs[i]).attr("value") + "&";
		}

		$.post("../email_invitations.php?u="+user, data, function(status) { document.invitations.submit(); });
	} else {
		return false;
	}
}

function generatePassword(length) {

    var sPassword = "";

    var noPunction = 1;

    for (i=0; i < length; i++) {
        numI = getRandomNum();
        if (noPunction) { while (checkPunc(numI)) { numI = getRandomNum(); } }
        sPassword = sPassword + String.fromCharCode(numI);
    }
    return sPassword;
}

function getRandomNum() {
	var rndNum = Math.random();
    rndNum = parseInt(rndNum * 1000);
    rndNum = (rndNum % 94) + 33;
    return rndNum;
}

function checkPunc(num) {
    if ((num >=33) && (num <=47)) { return true; }
    if ((num >=58) && (num <=64)) { return true; }
    if ((num >=91) && (num <=96)) { return true; }
    if ((num >=123) && (num <=126)) { return true; }
    return false;
}

function toggleVideoThumb(id, count) {

}

function updateTranscript(url) {
	$("#transcript_url").attr('href',url);
}

// function to add/remove stylesheet and stores cookie
function fontSizer(font,reload) {

	if (font) {

		// Had to add a reloader because IE6 sometimes only resized half the fonts until the page was reloaded.
		if (reload != false)
		{
			Set_Cookie( 'ptaFontSize', font, 30, '/', '', '' );
			window.location.reload();
		}
		else
		{
			switch (font) {
			case 1:
				$("#fontSizer").remove();
				$("head").append('<link href="/styles/fontsize0.css" rel="stylesheet" type="text/css" id="fontSizer" />');
				break;
			case 2:
				$("#fontSizer").remove();
				$("head").append('<link href="/styles/fontsize1.css" rel="stylesheet" type="text/css" id="fontSizer" />');
				break;
			case 3:
				$("#fontSizer").remove();
				$("head").append('<link href="/styles/fontsize2.css" rel="stylesheet" type="text/css" id="fontSizer" />');
				break;
			default:
				$("#fontSizer").remove();
				break;
			}
		}
	} else {
		// check for cookie
		if ( Get_Cookie( 'ptaFontSize' ) ) {
			fontSizer(parseInt(Get_Cookie('ptaFontSize')),false);
		}
	}
}

function Set_Cookie( name, value, expires, path, domain, secure ) {
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );

	/*
	if the expires variable is set, make the correct
	expires time, the current script below will set
	it for x number of days, to make it for hours,
	delete * 24, for minutes, delete * 60 * 24
	*/
	if ( expires )
	{
	expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );

	document.cookie = name + "=" +escape( value ) +
	( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
	( ( path ) ? ";path=" + path : "" ) +
	( ( domain ) ? ";domain=" + domain : "" ) +
	( ( secure ) ? ";secure" : "" );
}

function Delete_Cookie( name, path, domain ) {
	if ( Get_Cookie( name ) ) document.cookie = name + "=" +
	( ( path ) ? ";path=" + path : "") +
	( ( domain ) ? ";domain=" + domain : "" ) +
	";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

function Get_Cookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f

	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );


		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}

function dialogBlock(listsave) {

	$("#savelist").children("li").remove();

	for (i=0;i<listsave.length;i++) {
		$("#savelist").append('<li>' + listsave[i] + '</li>')
	}

	$.blockUI(dialog, { width: "465px", top: "20%", left:"40%", backgroundColor: "#000", opacity:"0.9" });

	$("#saveYes").click(function() {
		$.unblockUI();
		$("#savelist").children("li").remove();
	});

}

function hidePrompt() {
	if ($("input[name=hidePrompt]:checked").val() == 1) {
		Set_Cookie( 'ptaHidePrompt', 1, '', '/', '', '' );
	} else {
		Delete_Cookie('ptaHidePrompt','/','');
	}

}