// pinEdit
function submitPinEdit() {
	if (document.getElementById("pinEditCMS") && document.getElementById("pinEditField")) {
		document.getElementById("pinEditField").value = document.getElementById("pinEditCMS").contentWindow.editGetHtmlBody();
	}
	return true;
}


// Make this my homepage
function makeThisMyHomepage(el) {
	if (document.all) {
		el.style.behavior='url(#default#homepage)';
		el.setHomePage(window.location.href);
	}else 
		alert('This link only works in Internet Explorer.\nTHANK YOU FOR NOT USING INTERNET EXPLORER\nYou are making the internet better.\n------------\nYou should be able to set this page as your home-page \nby dragging the icon in the location-bar to your home button.');
}


// Show photos for photo-set
function showphotos(psid) {
	var looptarg = document.getElementById("photosetlist");
	for (var x = 0; x <= looptarg.childNodes.length; x++) {
		var node = looptarg.childNodes[x];
		if (node && node.nodeName == "TR") {
			if (node.id.indexOf("photo") != -1) {
				node.style.display = node.id == psid ? "block" : "none";
			}
		}
	}
}


/**
* Function : dump()
* Arguments: The data - array,hash(associative array),object
*    The level - OPTIONAL
* Returns  : The textual representation of the array.
* This function was inspired by the print_r function of PHP.
* This will accept some data as the argument and return a
* text that will be a more readable version of the
* array/hash/object that is given.
*/
function dump(arr,level) {
var dumped_text = "";
if(!level) level = 0;

//The padding given at the beginning of the line.
var level_padding = "";
for(var j=0;j<level+1;j++) level_padding += "    ";

if(typeof(arr) == 'object') { //Array/Hashes/Objects
 for(var item in arr) {
  var value = arr[item];
 
  if(typeof(value) == 'object') { //If it is an array,
   dumped_text += level_padding + "'" + item + "' ...\n";
   dumped_text += dump(value,level+1);
  } else {
   dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
  }
 }
} else { //Stings/Chars/Numbers etc.
 dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
}
return dumped_text;
} 


/* ==================================================== */
// ::: Changes multi-select form elements to a more usable element
// :::
// ::: coded by Kae - kae@verens.com
// ::: I'd appreciate any feedback.
// ::: You have the right to include this in your sites.
// ::: Please retain this notice.
/* ==================================================== */

/* edit these variables to customise the multiselect */ {
 var show_toplinks=false;
}

/* global variables - do not touch */ {
 var isIE=window.attachEvent?true:false;
 var selectDefaults=[];
}
function addEvent(el,ev,fn){
 if(isIE)el.attachEvent('on'+ev,fn);
 else if(el.addEventListener)el.addEventListener(ev,fn,false);
}

function buildMultiselects(){
 do{
  found=0;
  a=document.getElementsByTagName('select');
  for(b=0;b<a.length,!found;b++){
   var ms=a[b];
   if(ms==null)break;
   var name=ms.name.substring(0,ms.name.length-2);
   if(ms.multiple){
    /* common variables */ {
     selectDefaults[name]=[];
     var found=1,disabled=ms.disabled?1:0,width=ms.offsetWidth,height=ms.offsetHeight;
     if(width<150)width=150;
     if(height<100)height=100;
    }
    /* set up wrapper */ {
     var wrapper=document.createElement('span');
	 wrapper.className+=" multiselect";
     wrapper.style.width=width+"px";
     wrapper.style.height=height+"px";
     wrapper.style.position='relative';
     /*wrapper.style.border="1px solid #CCC";
     wrapper.style.font="10px sans-serif";*/
    }
    if(show_toplinks){ /* reset, all, none */
	 wrapper.appendChild(newLink("javascript:"+(disabled?"alert('selection disabled')":"multiselect_selectall('"+name+"','checked');"),'all'));
     wrapper.appendChild(document.createTextNode(', '));
     wrapper.appendChild(newLink("javascript:"+(disabled?"alert('selection disabled')":"multiselect_selectall('"+name+"','');"),'none'));
     wrapper.appendChild(document.createTextNode(', '));
     wrapper.appendChild(newLink("javascript:"+(disabled?"alert('selection disabled')":"multiselect_selectall('"+name+"','reset');"),'reset'));
    }
    /* setup multiselect */ {
     newmultiselect=document.createElement('div');
     //newmultiselect.style.position='absolute';
     newmultiselect.style.top=show_toplinks?'15px':'0';
     newmultiselect.style.left='0';
     newmultiselect.style.overflow='auto';
     newmultiselect.style.width=(isIE?width-4:width)+"px";
     newmultiselect.style.height=show_toplinks?height-(isIE?19:15)+"px":height+'px';
    }
    c=ms.getElementsByTagName('option');
    for(d=0;d<c.length;d++){
     var label=document.createElement('label');
     label.style.display="block";
     /*label.style.border="1px solid #eee";
     label.style.borderWidth="1px 0";
     label.style.font="10px arial";
     label.style.lineHeight="10px";
     label.style.paddingLeft="20px";*/
     checkbox=document.createElement('input');
     checkbox.type="checkbox";
     if(c[d].selected){
      checkbox.checked="checked";
      checkbox.defaultChecked=true;
     }
     if(c[d].disabled){
      checkbox.disabled='disabled';
      label.style.color='#666';
     }
     selectDefaults[name][d]=c[d].selected?'checked':'';
     if(disabled)checkbox.disabled="disabled";
     checkbox.value=c[d].value;
     /*checkbox.style.marginLeft="-16px";
     checkbox.style.marginTop="-2px";*/
     checkbox.name=ms.name;

     // escape the label
     var text=c[d].innerHTML;
     text=text.replace(/\&nbsp;?/g,' ');
     text=text.replace(/\&lt;?/g,'<');
     text=text.replace(/\&gt;?/g,'>');

     labelText=document.createTextNode(text);
     label.appendChild(checkbox);
     label.appendChild(labelText);
     newmultiselect.appendChild(label);
    }
   wrapper.appendChild(newmultiselect);
   ms.parentNode.insertBefore(wrapper,ms);
   ms.parentNode.removeChild(ms);
   }
  }
 }while(found);
}

function multiselect_selectall(name,val){
 var els=document.getElementsByTagName('input'),found=0;
 for(var i=0;i<els.length;++i){
  if(els[i].name==name+'[]' || els[i].name==name)els[i].checked=val=='reset'?selectDefaults[name][found++]:val;
 }
}
function newLink(href,text){
 var e=document.createElement('a');e.href=href;e.appendChild(document.createTextNode(text));return e;
}
addEvent(window,'load',buildMultiselects);


function update_email_progress_bar(email_id) {
	$.ajax({
		async: true,
		type: "GET",
		url: "/a/send-email-progress/?email_id="+email_id,
		dataType: "json",
		cache: false,
		success: function (data) {
			$("#send-email-progress .progress div").css("width", data.percent+"%");
			if (data.percent == 100) {
				$("#send-email-progress h2").css("background", "transparent url(/img/tick.png) 0 50% no-repeat");
				$("#send-email-progress em").html(
					//+data.progress+" / "+data.total+" * 100 = "+data.percent
					"Complete. "+data.failed+" failed, successfully sent to "+data.success
					+" of "+data.total+" recipients."
				);
				$("#send-email-progress").append("<p><a href=\"/admin/email\">Complete! Return to email campaigns &gt;</a></p>");
			}else {
				$("#send-email-progress em").text(
					"Sending email to "+data.current
					+", "+data.failed+" failed, successfully sent to "+data.success
					+" of "+data.total+" recipients"
				);
				update_email_progress_bar(email_id);
			}
		},
		error: function (XMLHttpRequest, textStatus, errorThrown) {
			$("#send-email-progress em").html(
				"An <strong>unknown error</strong> has occured while UPDATING EMAIL PROGRESS, please contact system administrator.<br />"
				+"textStatus: "+textStatus+"<br />"
				+"errorThrown: "+errorThrown+"<br />"
			);
		}
	});
}


// Unobtrusive jquery 
jQuery(document).ready(function() {
	
	$('span.nospam span').replaceWith('@');
	$('span.nospam').each(function(x){
		var email = $(this).text();
		$(this).replaceWith('<a href="mailto:'+email+'">'+email+'</a>');
	});

	if ($("textarea[name=email_content]").length == 1) {
		$("textarea[name=email_content]").attr('id', 'email_content');
		var emaileditor = CKEDITOR.replace(
			'email_content',
			{
				height: '400px',
				uiColor: '#00AEEF',
				toolbar :
				[
					/*['Source','-','Save','NewPage','Preview','-','Templates'],
					['Cut','Copy','Paste','PasteText','PasteFromWord','-','Print', 'SpellChecker', 'Scayt'],
					['Undo','Redo','-','Find','Replace','-','SelectAll','RemoveFormat'],
					['Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton', 'HiddenField'],
					'/',
					['Bold','Italic','Underline','Strike','-','Subscript','Superscript'],
					['NumberedList','BulletedList','-','Outdent','Indent','Blockquote'],
					['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'],
					['Link','Unlink','Anchor'],
					['Image','Flash','Table','HorizontalRule','Smiley','SpecialChar','PageBreak'],
					'/',
					['Styles','Format','Font','FontSize'],
					['TextColor','BGColor'],
					['Maximize', 'ShowBlocks','-','About']*/
					
					['Link','Unlink','Anchor'],
					['Image','Table','HorizontalRule'],
					['Cut','Copy','Paste','PasteText','PasteFromWord','-','SpellChecker'],
					['Undo','Redo','RemoveFormat'],
					['Maximize', 'ShowBlocks','Source'],
					['Font','FontSize','TextColor','BGColor'],
					['Bold','Italic','Underline','Strike'],
					['NumberedList','BulletedList','-','Outdent','Indent','Blockquote'],
					['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock']
				]
			}
		);
		CKFinder.SetupCKEditor( emaileditor, '/inc/classes/ckfinder/' );
	}
	
	// video BE
	$('#manage-videos').tabs();
	$('#admin-video .mod_nav').append(
		"<div id=\"cat_save_response\">"
		+"<img src=\"\" alt=\"\" /> "
		+"<em>Click+Drag tabs to change their order</em>"
		+"</div>"
	);
	$('#manage-videos .ui-tabs-nav').sortable({
		update: function (event, ui) {
			
			// add response
			$("#cat_save_response em").text("Saving category order");
			$("#cat_save_response img").attr("src", "/img/ajax-loader.gif");
			
			// get order
			var ids = [], unassigned_pos, count;
			count = $('#manage-videos .ui-tabs-nav li').length;
			$('#manage-videos .ui-tabs-nav a').each(function(x){
				if ($(this).attr("href") == "#unassigned") {
					unassigned_pos = x;
				}else {
					ids[ ids.length ] = $(this).attr("href").replace(/#cat/,'');
				}
			});
			
			// ensure "unassigned" tab stays at bottom
			if ((unassigned_pos+1)!=count)
				$('#manage-videos .ui-tabs-nav li.unassigned').remove().appendTo('#manage-videos .ui-tabs-nav');
				
			// save
			$.ajax({
				type: "POST",
				url: "/a/save-video-cat-order",
				dataType: "text",
				data: {"cats[]": ids},
				success: function(data){
					$("#cat_save_response em").text("Saved category order");
					$("#cat_save_response img").attr("src", "/img/accept.png");
				},
				error: function(XMLHttpRequest, textStatus, errorThrown){
					$("#cat_save_response em").text("Error \""+textStatus+"\" while saving category order");
					$("#cat_save_response img").attr("src", "/img/exclamation.png");
				}
			});
		}
	});
	
	// video FE
	$('#video-tabs').tabs();
	$('#video-tabs .tab').append("<div style=\"height:1px;line-height:1px;overflow:hidden;clear:both;\">&nbsp;</div>");
	/*$('#video-tabs .playlist a').click(function(){
		var player_id = $("object[data*='video.nzskier.com']").attr("id");
		var player = document.getElementById(player_id);
		var uri = $(this).attr("href");
		if ($(this).attr("class").indexOf("embed") > -1) {
			//alert("embed link");
			var file = $(this).attr("class");
		}else {
			//alert("standard link");
			var file = 'http://video.nzskier.com/flv/'+$(this).attr("class");
		}
		player.sendEvent("STOP","true");
		player.sendEvent('LOAD', {
				'file':			file,
				'link':			uri,
				'viral.link':	uri,
				'fbit.link':	uri,
				'tweetit.link':	uri
			}
		);
		player.sendEvent("PLAY","true");
		return false;
	});*/
	
	// unobtrusive youtube
	$('body').youtubeLinksToEmbed();
	
	// email system
	// check selected recipients onload
	var count = 0;
	$('#recipients input:checked').each(function() {
		$(this).parent().toggleClass("selected");
		count ++;
	});
	// update selected count
	$('#recipients strong span').text(count);
	// checkbox change
	$('#recipients input').change(function(){
		$(this).parent().toggleClass("selected");
		var count = $('#recipients strong span').text();
		count = count * 1;
		count += $(this).attr("checked") ? 1 : -1;
		$('#recipients strong span').text(count);
	});
	// select all/none function
	$('#recipients a').click(function(){
		var count = 0;
		var selectall = $(this).text() == "select all" ? true : false;
		$('#recipients input').each(function() {
			if (selectall) {
				count ++;
				$(this).attr("checked", true);
				$(this).parent().addClass("selected");
			}else {
				$(this).attr("checked", false);
				$(this).parent().removeClass("selected");
			}
		});
		$('#recipients strong span').text(count);
		return false;
	});
	$("#email-history a.error, #email-history a.other").click(function(){
		// init thickbox progress info
		tb_show('','#TB_inline?modal=true&height=150&width=600&inlineId=send-email-progress-thickbox','null');
		// update response
		$("#send-email-progress em").text("Attempting to re-send email...");
		// start sending
		var email_id = $(this).parent().parent().attr("id").replace("email#","");
		$.ajax({
			type: "GET",
			url: "/a/send-email/?email_id="+email_id,
			cache: false,
			error: function (XMLHttpRequest, textStatus, errorThrown) {
				$("#send-email-progress em").html(
					"An <strong>unknown error</strong> has occured while SENDING EMAIL, please contact system administrator.<br />"
					+"textStatus: "+textStatus+"<br />"
					+"errorThrown: "+errorThrown+"<br />"
				);
			}
		});
		setTimeout(update_email_progress_bar(email_id), 5000);
		return false;
	});
	// send mail with progress
	$('form#send-email-campaign').submit(function() {
		// update email content from editor
		$("#email_content").attr('value', CKEDITOR.instances.email_content.getData());
		// validate form
		if (
			!$("input[name=ref]").attr("value")
			|| !$("input[name=subject]").attr("value")
			|| !$("input[name=reply_to]").attr("value")
			|| !$("textarea[name=email_content]").attr("value")
		) {
			alert("You must complete required fields to continue");
			return false;
		}
		if (!$('#recipients input:checked').length) {
			alert("You must select recipients to continue");
			return false;
		}
		// init thickbox progress info
		tb_show('','#TB_inline?modal=true&height=150&width=600&inlineId=send-email-progress-thickbox','null');
		// submit the form 
		$(this).ajaxSubmit({
			async: false,
			dataType: 'json',
			cache: false,
			success: function (data) {
				if (data.id) {
					$("#send-email-progress em").text("Email saved successfully, now sending");
					$.ajax({
						type: "GET",
						url: "/a/send-email/?email_id="+data.id,
						cache: false,
						error: function (XMLHttpRequest, textStatus, errorThrown) {
							$("#send-email-progress em").html(
						  		"An <strong>unknown error</strong> has occured while SENDING EMAIL, please contact system administrator.<br />"
								+"textStatus: "+textStatus+"<br />"
								+"errorThrown: "+errorThrown+"<br />"
							);
						}
					});
					update_email_progress_bar(data.id);
				}
			},
			error: function (XMLHttpRequest, textStatus, errorThrown) {
			  $("#send-email-progress em").html(
			  	"An <strong>unknown error</strong> has occured while SAVING EMAIL, please contact system administrator.<br />"
			  	+"textStatus: "+textStatus+"<br />"
			  	+"errorThrown: "+errorThrown
			  );
			}
		});
		// return false to prevent normal browser submit and page navigation 
		return false;
	});
	
	// wymeditor
	if ($('.wym').length > 0) {
		$('.wym').wymeditor({
			
			skin: 'nzsnow',
			iframeBasePath: '/inc/classes/wymeditor/iframe/nzsnow/',
			stylesheet: '/inc/classes/wymeditor/iframe/nzsnow/wymiframe.css',
			
			dialogHtml: "<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Strict//EN'\n"
				+ " 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'>\n"
				+ "<html>\n"
				+ "<head>\n"
				+ "<title>"	+ WYMeditor.DIALOG_TITLE + "</title>\n"
				+ "<link rel='stylesheet' type='text/css' media='screen' href='/inc/classes/wymeditor/skins/nzsnow/" + WYMeditor.SKINS_DEFAULT_CSS + "' />\n"
				+ "<link rel='stylesheet' type='text/css' media='screen' href='" + WYMeditor.BASE_PATH + "plugins/imgmgr/imgmgr.css' />\n"
				+ "<script type='text/javascript'>\n"
				+ "var WYMeditor_BASE_PATH = '"+WYMeditor.BASE_PATH+"';\n"
				+ "</script>\n"
				+ "<script type='text/javascript' src='" + WYMeditor.JQUERY_PATH + "'></script>\n"
				+ "<script type='text/javascript' src='" + WYMeditor.BASE_PATH + "jquery.wymeditor.pack.js'></script>\n"
				+ "<script type='text/javascript' src='" + WYMeditor.BASE_PATH + "plugins/imgmgr/ui.core.packed.js'></script>\n"
				+ "<script type='text/javascript' src='" + WYMeditor.BASE_PATH + "plugins/imgmgr/ui.tabs.packed.js'></script>\n"
				+ "<script type='text/javascript' src='" + WYMeditor.BASE_PATH + "plugins/imgmgr/ajaxfileupload.js'></script>\n"
				+ "<script type='text/javascript' src='" + WYMeditor.BASE_PATH + "plugins/imgmgr/jquery.wymeditor.imgmgr.js'></script>\n"
				+ "</head>\n"
				+ WYMeditor.DIALOG_BODY
				+ "</html>",

			toolsItems: [
				{'name': 'Bold', 'title': 'Strong', 'css': 'wym_tools_strong'}, 
				{'name': 'Italic', 'title': 'Emphasis', 'css': 'wym_tools_emphasis'},
				{'name': 'InsertOrderedList', 'title': 'Ordered_List', 'css': 'wym_tools_ordered_list'},
				{'name': 'InsertUnorderedList', 'title': 'Unordered_List', 'css': 'wym_tools_unordered_list'},
				{'name': 'Indent', 'title': 'Indent', 'css': 'wym_tools_indent'},
				{'name': 'Outdent', 'title': 'Outdent', 'css': 'wym_tools_outdent'},
				{'name': 'Undo', 'title': 'Undo', 'css': 'wym_tools_undo'},
				{'name': 'Redo', 'title': 'Redo', 'css': 'wym_tools_redo'},
				{'name': 'CreateLink', 'title': 'Link', 'css': 'wym_tools_link'},
				{'name': 'Unlink', 'title': 'Unlink', 'css': 'wym_tools_unlink'},
				{'name': 'InsertImage', 'title': 'Image', 'css': 'wym_tools_image'},
				{'name': 'InsertTable', 'title': 'Table', 'css': 'wym_tools_table'},
				{'name': 'Paste', 'title': 'Paste_From_Word', 'css': 'wym_tools_paste'},
				{'name': 'ToggleHtml', 'title': 'HTML', 'css': 'wym_tools_html'},
				{'name': 'Preview', 'title': 'Preview', 'css': 'wym_tools_preview'}
			],
			
			postInit: function(wym) {
				wym.hovertools();
				wym.resizable();
			}

		});
	}

	// auto-clear fields
	$(".autoclear").attr("title", function(){ return this.value; });
	$("input[type=password].autoclear").addClass("autoclearpw"); 
	//$(".autoclearpw").attr("type","text");
	$(".autoclear").focus(function() {
		if (this.value == this.title) {
			this.value = "";
			$(this).removeClass("autoclear");
			if (this.className.indexOf("autoclearpw") > -1)
				this.type = "password";
		}
	});
	$(".autoclear").blur(function() {
		if (this.value == this.title || this.value == "") {
			this.value = this.title;
			$(this).addClass("autoclear");
			if (this.className.indexOf("autoclearpw") > -1)
				this.type = "text";
		}
	});
	
	// topic tracking remove
	$("a[href*=/a/untrack-topic]").click(function() {
		
		// confirm
		if (!confirm("Do you really want to stop tracking this topic?"))
			return false;
		
		// send request
		var ajaxresult = $.post(this.href, {ajax: 1}, function(xml) {
			alert( $("response", xml).text() );
			return $("result", xml).text() == "success" ? TRUE : FALSE;
		});
		
		// hide row
		if (ajaxresult && this.parentNode.parentNode.nodeName == "TR")
			this.parentNode.parentNode.style.display="none";
		
		// don't goto link
		return false;
		
	});
	
	// topic tracking email notifications
	$(".topic-track-email input").change(function() {
		
		// send request
		$.post("/a/track-topic-email/"+this.value, {trackemail: (this.checked?1:0)}, function(xml) {
			alert( $("response", xml).text() );
		});
		
	});
	
	// remember me checkbox on login
	$("[name=rememberme]").change(function() {
		if (this.checked == true) {
			var message = "";
			message += "If you choose to be remembered on this computer \n";
			message += "you are liable for any actions carried out while \n";
			message += "logged in as this user.";
			if (!confirm(message))
				this.checked = false;
		}
	});
	
	// zebra rows
	$("table.zebra tr:even").addClass("zebra1");
	$("table.zebra tr:odd").addClass("zebra2");
	$("div.zebra > :even").addClass("zebra1");
	$("div.zebra > :odd").addClass("zebra2");
	
	
	$("#snowreports table tfoot tr").click(function(){
		window.open(
			$(this).find("a").attr("href"),
			"snowreports",
			"width=1024,height=500,scrollbars,resizable"
		);
	});
	$("#snowreports table tfoot tr a").click(function(){ 
		window.open(
			$(this).attr("href"),
			"snowreports",
			"width=1000,height=500,scrollbars,resizable"
		);
		return false; 
	});
	
	// webcams
	$("#latestcams a.resort").click(function(){
		window.open(
			$(this).attr("href"),
			"resort",
			"width=800,height=600,resizable,scrollbars"
		);
		return false;
	});
	$("#latestcams a.enlarge").click(function(){
		$("#latestcams div.first a").attr("href", $("a.resort", $(this).parent()).attr("href"));
		$("#latestcams div.first img").attr("src", $(this).attr("href"));
		$("#latestcams div.first span").text($("span", $(this).parent()).text());
		return false;
	});
	
	// non-obtrusive popups/new-windows
	$("a.new-window").click(function(){
		var url = $(this).attr("href");
		window.open(url, url, "width=800,height=600,scrollbars,resizable");
		return false;
	});
	$("a.small-popup").click(function(){
		var winl = (screen.width - 400) / 2;
     	var wint = (screen.height - 300) / 2;
		var url = $(this).attr("href");
		window.open(url, url, "width=400,height=300,scrollbars=1,resizable=1,top="+wint+",left="+winl);
		return false;
	});
	
	// star ratings
	$(".star-rating a").hover(
		function(){
			if ($(this).parents(".rated").get(0))
				return false;
			var starcont = $(this).parents(".star-rating").get(0);
			$("a.set", starcont).addClass("set-over");
			$("a.set", starcont).removeClass("set");
			if (!$("body.valid-user").get(0)) {
				$(".status", starcont).attr("title", $(".status", starcont).text());
				$(".status", starcont).html("<strong>Login to rate this story</strong>");
			}
			var xindex = this;
			$("a", starcont).each(function(yindex){
				$(this).addClass("over");
				if ($(xindex).attr("href") == $(this).attr("href"))
					return false;
			});
		},
		function(){
			var starcont = $(this).parents(".star-rating").get(0);
			$("a.set-over", starcont).addClass("set");
			$("a.set-over", starcont).removeClass("set-over");
			$("a", starcont).removeClass("over");
			$(starcont).removeClass("over");
			if (!$("body.valid-user").get(0)) {
				$(".status", starcont).html($(".status", starcont).attr("title"));
			}
		}
	);
	$(".star-rating a").click(function(){
		if ($(this).parents(".rated").get(0))
			return false;
		if (!$("body.valid-user").get(0)) {
			window.location.href = "/smmhdc/login";
			return false;
		}
		var starcont = $(this).parents(".star-rating").get(0);
		var starlink = this;
		var rateurl = $(this).attr("href");
		var randNum = Math.random();
		$.ajax({
			type : "POST",
			data: { "hash" : randNum },
			url : rateurl,
			dataType : "text",
			success : function (data, textStatus) {
				if (data == "success") {
					$(".status", starcont).html("<strong>Thanks for your rating!</strong>");
					$(starcont).addClass("rated");
				}
			},
			error : function (XMLHttpRequest, textStatus, errorThrown) {
			  alert("An error occurred: "+XMLHttpRequest.responseText);
			}
		});
		return false;
	});
	
});
