// 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('http://www.nzsnowboard.com');
	}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<60)height=60;
    }
    /* 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 />"
			);
		}
	});
}


var weathover = new Array();
function weatherout(lid) {
	$('#weather pre').text($('#weather pre').text()+'\nweatherout('+lid+'):'+weathover[ lid ]); // DEBUG
	if (lid && weathover[ lid ])
		setTimeout('weatherout("'+lid+'")', 1000);
	else
		$('#weather div#'+lid).fadeOut(function(){ $('#weather div#'+lid).remove(); });
}


// Unobtrusive jquery 
jQuery(document).ready(function() {

	// weather map
	$('#weather li a').click(function(){
		var location = $(this).attr('href');
		var fieldname = $(this).text();
		window.open(
			location,
			fieldname,
			"width=1024,height=500,scrollbars,resizable"
		);
		return false;
	});
	//$('#weather').append('<pre style="width:auto;background-color:rgba(0,0,0,0.5);font-family:monospace;font-size:9px;line-height:1;position:absolute;top:5px;left:5px;color:#FFF">LOAD: '+weathover+'</pre>'); // DEBUG
	//$('#weather pre').click(function(){ $(this).text(''); }); // DEBUG
	$('#weather li').hover(function(){
		
		var location = $(this).text().replace(' ','%20');
		var lid = $(this).text().replace(' ','');
		
		$('#weather div').remove();
		weathover = new Array();
		weathover[ lid ] = true;
		
		//$('#weather pre').text($('#weather pre').text()+'\n'+lid+' LI HOVER:'+weathover[ lid ]); // DEBUG
		
		var xw = $(this).width()*1;
		var xh = $(this).height()*1;
		
		var cx = (($(this).css('left').replace('px','')*1) + xw) - 95;
		var cy = (($(this).css('top').replace('px','')*1) + xh) - 3;
		
		$('#weather').append(
			'<div id="'+lid+'" style="display:none;left:'+cx+'px;top:'+cy+'px;">'
			+'<iframe id="weatherwidget" style="width:100px;height:175px;border:none;" frameborder="0" scrolling="no"></iframe>'
			+'<img src="/img/ajax-loader.gif" />'
			+'</div>'
		);
		
		$('#weather div').hover(function(){
			weathover[ lid ] = true;
			//$('#weather pre').text($('#weather pre').text()+'\n'+lid+' DIV HOVER:'+weathover[ lid ]); // DEBUG
		},function(){
			weathover[ lid ] = false;
			//$('#weather pre').text($('#weather pre').text()+'\n'+lid+' DIV OUT:'+weathover[ lid ]); // DEBUG
		});
		
		$('#weather div').fadeIn(function(){
			$('iframe#weatherwidget').attr('src', 'http://www.mountainwatch.com:80/widgets/forecast-widget-small.jsp?location='+location);
			$('iframe#weatherwidget').load(function(){
				$('#weather div img').remove();
			});
		});
	}, function() {
		
		var location = $(this).text().replace(' ','%20');
		var lid = $(this).text().replace(' ','');
		weathover[ lid ] = false;
		
		//$('#weather pre').text($('#weather pre').text()+'\n'+lid+' LI OUT:'+weathover[ lid ]); // DEBUG
		setTimeout('weatherout("'+lid+'")', 1000);
	});
	
	// confirm deletes
	$('a.delete').click(function(){
		
		// confirm
		if (!confirm("This action cannot be undone!\nAre you sure you want to delete this?"))
			return false;
		
		// ajax
		
		// delete listing
		if ($(this).attr('href').indexOf('delete-listing-category') > -1) {
			var xurl = $(this).attr('href');
			var xa = this;
			$.get(xurl, function() { $(xa).parent().parent().hide('slow'); });
			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() {
		// 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
	$('.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(); // other plugins...
				wym.resizable({handles: "s,e",
							   maxHeight: 600});
			}

	});

	// 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, "new-window", "left=0,top=0,width=1000,height=800,location=yes,menubar=yes,resizable=yes,scrollbars=yes,status=yes,titlebar=yes,toolbar=yes");
		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, "new-window", "width=400,height=300,scrollbars=1,resizable=1,top="+wint+",left="+winl);
		return false;
	});
	
});
