$(document).ready(function() {
	
	$(".hidden").slideUp();
	
	$("#openads").bind("click", function() {
		if ($("#theads").css("display") == "none") {
			$("#theads").slideDown();	
		} else {
			$("#theads").slideUp();
		}
		return false;
	});
    $("#openeditor, .openeditor").bind("click", function() {
		$("#theeditor").slideToggle();	
		return false;
	});
	
	$(".widget .head a").bind("click", function() {
		$(".sliderContainer").css("width","258px").css("height","85px");
		if ($(this).parent().parent().children(".body").css("display") == "none") {
			$(this).parent().parent().children(".body").slideDown(300, function() {
				updateWidgetCookie();
			});	
		} else {
			$(this).parent().parent().children(".body").slideUp(300, function() {
				updateWidgetCookie();
			});	
		}
		return false;
	});
	
	$("#newsSlider").easySlider({
		controlsBefore:	'<p id="controls">',
		controlsAfter:	'</p>'
	});
	$("#caseSlider").easySlider({
		controlsBefore:	'<p id="controls2">',
		controlsAfter:	'</p>',
		prevId: 'prevBtn2',
		nextId: 'nextBtn2'
	});
    $("#blogSlider").easySlider({
		controlsBefore:	'<p id="controls3">',
		controlsAfter:	'</p>',
		prevId: 'prevBtn3',
		nextId: 'nextBtn3'
	});
    $("#feedSlider").easySlider({
		controlsBefore:	'<p id="controls4">',
		controlsAfter:	'</p>',
		prevId: 'prevBtn4',
		nextId: 'nextBtn4'
	});
    
    $(".links-menu li").bind("mouseover", function() {
        var id = $(this).attr("id");
        $(".links-info").hide();
        $("#"+id+"d").show();
        $(this).parent().children("li").removeClass("active");
        $(this).addClass("active");
    });
    $(".links-menu li").bind("click", function() { return false; })
	
    
    $(".titlebar span").bind("click", function() {
       $(this).parent().parent().children(".panel-body").slideToggle(); 
    });
    $(".related .panel-body .tabs li").bind("click", function() {
        $(".related .panel-body .tabs li").removeClass("active");
        $(this).addClass("active");
        var id = $(this).attr("id");
        $(".related .panel-body .related-panel").hide();
        $("#"+id+"p").show();  
    });
    
    $(".minitabs li").bind("click", function() {
        $(this).parent().children("li").removeClass("active");
        $(this).addClass("active");
        var id = $(this).attr("id");
        $(this).parent().parent().children(".minitab").hide();
        $("#"+id+"p").show();  
    });
    
    $("#feedClose").bind("click", function() { $(this).parent().parent().parent().slideUp(); });
    $("#feedEdit").bind("click", function() { $("#feed_editor").slideToggle(); });
    
    $("input[id^='hlp_']").bind("click", function() {
        var pos = $(this).position();
        var id = $(this).attr("id");
        
        $.post('/common/ajax/help.php','code='+id.substring(4),function(data, status) {
            $("#help-title").html(data.title);
            $("#help-instructions").html(data.helptext);
            if (data.direction == 'rtl') {
                $("#help-panel").css("left", (pos.left-25)+"px").css("top",(pos.top-210)+"px").show();
            } else {
                $("#help-panel").css("left", (pos.left-310)+"px").css("top",(pos.top-210)+"px").show();
            }
        },'json')
        
        
    });
    
    $("#help-close a").bind("click", function() { $("#help-panel").hide(); return false; });
});

function updateWidgetCookie() {
	
	var data = '';
	
	$(".widget .head a").each(function () {
		var id = $(this).parent().parent().attr("id");
		var state = $(this).parent().parent().children(".body").css("display");
		data += id + "=" + state +";";
	}); 	

	Set_Cookie('lwsaWidgetState',data,30);
}

// COOKIE FUNCTIONS
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 gotoStep(step, required) {
	var err = 0;

	if (required) {
		
		var req = required.split(',');
		if (req.length > 0) {
			for (i=0;i<req.length;i++) {
				if ($("input[name="+req[i]+"]:checked").val() == undefined) {
					err++;
				}
			}	
		}
			
	}
	
	if (err > 0) {
		$("#quizerr").show();
	} else {
		$("#quizerr").hide();
		$(".quiz-step").hide();
		$("#step"+step).show();	
	}
	
	
}

function showSkillResults() {
	
	// Questions 1 - 6
	var individual = 0;
	var team = 0;
	
	for (i=1; i<7; i++) {
		var val = $("input[name=q"+i+"]:checked").val();
		if (val && val != 0) {
			var v = val.substring(0,1);
			var t = val.substring(1);
			
			if (t == 'i') {
				individual = parseInt(individual) + parseInt(v);
			} else {
				team = parseInt(team) + parseInt(v);
			}
		}
	}
	
	var indpro = Math.round((individual / 12) * 100);
	var teampro = Math.round((team / 12) * 100);
	$("#indscore").html(indpro+"%");
	$("#teamscore").html(teampro+"%");
	$("#individual-bar span").css("width","0px").animate({"width": ((485 / 100) * indpro)+"px"}, {duration: "slow"});
	$("#team-bar span").css("width","0px").animate({"width": ((485 / 100) * teampro)+"px"}, {duration: "slow"});
	
	// Questions 7 - 10
	var recog = $("input[name=q7]:checked").val();
	var life = $("input[name=q8]:checked").val();
	var friend = $("input[name=q9]:checked").val();
	var money = $("input[name=q10]:checked").val();
	var recogpro = Math.round((recog / 4) * 100);
	var lifepro = Math.round((life / 4) * 100);
	var friendpro = Math.round((friend / 4) * 100);
	var moneypro = Math.round((money / 4) * 100);
	$("#recogscore").html(recogpro+"%");
	$("#lifescore").html(lifepro+"%");
	$("#friendscore").html(friendpro+"%");
	$("#moneyscore").html(moneypro+"%");
	$("#recognition-bar span").css("width","0px").animate({"width": ((485 / 100) * recogpro)+"px"}, {duration: "slow"});
	$("#lifestyle-bar span").css("width","0px").animate({"width": ((485 / 100) * lifepro)+"px"}, {duration: "slow"});
	$("#friendship-bar span").css("width","0px").animate({"width": ((485 / 100) * friendpro)+"px"}, {duration: "slow"});
	$("#money-bar span").css("width","0px").animate({"width": ((485 / 100) * moneypro)+"px"}, {duration: "slow"});

	// Questions 11 - 25
	var seller = 0;
	var innovator = 0;
	var organiser = 0;
	
	for (i=11; i<16; i++) {
		var val = $("input[name=q"+i+"]:checked").val();
		if (val && val != 0) {
			seller = parseInt(seller) + parseInt(val);
		}
	}
	for (i=16; i<21; i++) {
		var val = $("input[name=q"+i+"]:checked").val();
		if (val && val != 0) {
			innovator = parseInt(innovator) + parseInt(val);
		}
	}
	for (i=21; i<26; i++) {
		var val = $("input[name=q"+i+"]:checked").val();
		if (val && val != 0) {
			organiser = parseInt(organiser) + parseInt(val);
		}
	}
	var seller = Math.round((seller / 20) * 100);
	var innovator = Math.round((innovator / 20) * 100);
	var organiser = Math.round((organiser / 20) * 100);
	$("#sellerscore").html(seller+"%");
	$("#innovatorscore").html(innovator+"%");
	$("#organiserscore").html(organiser+"%");
	$("#seller-bar span").css("width","0px").animate({"width": ((485 / 100) * seller)+"px"}, {duration: "slow"});
	$("#innovator-bar span").css("width","0px").animate({"width": ((485 / 100) * innovator)+"px"}, {duration: "slow"});
	$("#organiser-bar span").css("width","0px").animate({"width": ((485 / 100) * organiser)+"px"}, {duration: "slow"});
}

function showChoiceResults() {
	
	var total = 0;
	
	for (i=1; i<35; i++) {
		total = parseInt(total) + parseInt($("input[name=q"+i+"]:checked").val());					
	}
	
	total = Math.round(((total/34)*100));
	
	$("#score").html(total+"%");
	$("#score-bar span").css("width","0px").animate({"width": ((485 / 100) * total)+"px"}, {duration: "slow"});
	
	if (total < 40) {
		$("#lt40").show();
	}
	if (total > 40 && total < 60) {
		$("#gt40lt60").show();
	}
	if (total > 60) {
		$("#gt60").show();
	}
}

function animPanel(panel, direction) {
    
    $(".jqpanel").hide();
    $("#"+panel+" p.buttons a, #"+panel+" p.buttons a span").addClass("nobg");
    $("#"+panel+" .info").children().hide();
    $("#"+panel+" p.buttons").css("bottom","202px");
    
    if (direction == 'rtl') {
        $("#"+panel+" img").hide().css("right","-162px").show().animate({"right": "0"}, "slow", "linear", function() {
             $("#"+panel+" img").attr("filter", false);
             $("#"+panel+" p.buttons a, #"+panel+" p.buttons a span").removeClass("nobg");
             if ($.browser.msie) {
                $("#"+panel+" .info h3, #"+panel+" .info ul").show();
                
                $("#"+panel+" p.buttons").show().animate({"bottom":"20px"},"slow","easeOutBounce");
             } else {
                $("#"+panel+" .info h3, #"+panel+" .info ul").fadeIn(1000,function() {
                    $("#"+panel+" p.buttons").show().animate({"bottom":"20px"},"slow","easeOutBounce");
                });
             }
        });
    } else {
    
        $("#"+panel+" img").hide().css("left","-162px").show().animate({"left": "0"}, "slow", "linear", function() {
             $("#"+panel+" p.buttons a, #"+panel+" p.buttons a span").removeClass("nobg");
             if ($.browser.msie) {
                $("#"+panel+" .info h3, #"+panel+" .info ul").show();
                
                $("#"+panel+" p.buttons").show().animate({"bottom":"20px"},"slow","easeOutBounce");
             } else {
                $("#"+panel+" .info h3, #"+panel+" .info ul").fadeIn(1000,function() {
                    $("#"+panel+" p.buttons").show().animate({"bottom":"20px"},"slow","easeOutBounce");
                });
             }
        });
    }
    $("#"+panel+" .redbar").show();
    $("#"+panel).show();
    
}

/* AWARDS FUNCTIONS */
function check_length_all(){
	var countable = new Array();

	for (var i=0; i < countable.length; i++) {
		check_length(document.getElementById(countable[i]));
	};
}

function check_length(obj) { 
	var maxwords = 200;
	rem = document.getElementById(obj.name+'_remaining');
	var char_count = obj.value.length;
	var fullStr = obj.value + " ";
	var initial_whitespace_rExp = /^[^A-Za-z0-9]+/gi;
	var left_trimmedStr = fullStr.replace(initial_whitespace_rExp, "");
	var non_alphanumerics_rExp = rExp = /[^A-Za-z0-9]+/gi;
	var cleanedStr = left_trimmedStr.replace(non_alphanumerics_rExp, " ");
	var ary = cleanedStr.split(" ");

	var len = ary.length -1; 
	rem.innerHTML = maxwords - len; 
	if (len > maxwords) { 
		alert("Message in '" + obj.name + "' limited to " + maxwords + " words."); 
		ary = ary.slice(0,maxwords-1); 
		obj.value = ary.join(" "); // truncate additional words  
		rem.innerHTML = 0; 
		return false; 
	} 
	return true; 
}

function EntryForm(part) {
	
	$(".entry-form").hide();
	$("#form-part"+part).show();
	
	$("#myMenu li.active").removeClass();
	$("#myMenu #part"+part).addClass("active");
	
	if (part == 'video') {
		$("#shortlisted").hide();
	} else {
		$("#shortlisted").show();	
	}
	
	$('html').animate({scrollTop:0}, 'slow'); 
	
}

function saveEntry(next, hide) {
	var data = $("#entryform").serialize();  
    
	if (hide != 1)
		$("#saveAlert").show().pause(5000).fadeOut();
	
	$.post("/common/ajax/save_comp_entry.php", data, function(data,status) {
		// put save successful message up
		
		if (data.entryid) {
			$("#entryID").attr("value",data.entryid); // set the entryID for future saves
		}
		
		if (data.submitted == '1') {
			window.location='/home/awards/entry-form/complete/';
		}
	}, "json");
	
	if (next) {
		EntryForm(next);
	}

}

function SubmitEntry(next) {
    
    $("#errorAlert").hide();
    var errors = 0;
    
    var fname = $("#firstname").val();
    var sname = $("#surname").val();
    var address = $("#address").val();
    var email = $("#email").val();
    var bname = $("#businessname").val();
    var baddress = $("#businessaddress").val();
    var bpcode = $("#businesspostcode").val();
    var bmail = $("#businessemail").val();
    var btel = $("#businesstelno").val();
    var bweb = $("#businesswebsite").val();
    var bcomm = $("select[name=businesscommenced[day]").val()+"/"+$("select[name=businesscommenced[month]").val()+"/"+$("select[name=businesscommenced[year]").val();
    var struct = $("#businessstructure").val();
    var bdesc = $("#businessdescription").val();
    var bg = $("#background").val();
    var edu = $("#educationtraining").val();
    var market = $("#yourmarket").val();
    var inno = $("#innovation").val();
    var comp = $("#competitionsource").val();
    var means = $("#winningmeans").val();
    var sig = $("#signature").val();
    var dec = $("input[name=declarationconfirm]:checked").val();
    
    if (fname==''||sname==''||address==''||email==''||bname==''||baddress==''||bpcode==''||bmail==''||btel==''||bweb==''||bcomm==''||struct==''||bdesc==''||bg==''||edu==''||market==''||inno==''||comp==''||means==''||sig==''||dec=='undefined') {
        errors = 1;
    }
    
    if (errors > 0) {
        $("#errorAlert").show();       
    } else {
    
    	var data = $("#entryform").serialize();
    	
    	data += "&submit=1";
    
    	$.post("/common/ajax/save_comp_entry.php", data ,function(data,status){
    		// put save successful message up
    		$("#saveAlert").show().pause(5000).fadeOut();
    		
    		if (data.entryid) {
    			$("#entryID").val(data.entryid); // set the entryID for future saves
    		}
    		
    		if (data.submitted == '1') {
    			if (next) {
    				window.location='/home/awards/complete-ye/';
    			} else {
    				window.location='/home/awards/entry-form/complete/';
    			}
    			
    		}
    	}, 'json');
     }

}

function EntryPrint(id) {
	saveEntry('',1);
	
	if (id) {
		id = '?competitionID='+id;
	}
	
	window.open ("/home/awards/entry-form/print/"+id,"mywindow","status=1,resize=1,scrollbars=1"); 
}

function castVote(comp, user, entry) {
	
	$(".vote").hide();
	
	data = "compID="+comp+"&entryID="+entry+"&userID="+user;
	$.post("/common/ajax/cast_vote.php", data, function(data, status) {
		if (data == 'success') {
			$(".vote-cast").show().pause(3000).fadeOut('slow');
		} else {
			$(".vote").show();
		}
	});
	
}
