/*
W|W CMS 2.0 General JavaScript file.
Pat Collins <pat@walltowall.com>
Created 15 June 2007

Utilizes the jQuery JavaScript framework.
*/

var flash_duration = -1;
var menuDelayClose = 200;

$(document).ready(function(){
	
	// ===========================
	// = Global DOM Manipulation =
	// ===========================
	
	// Manipulate and attach behavior to Cake flash messages.
	$("div.message").each(function(){
		$(this).fadeTo(1, 0.9);
		// var msg = $(this);
		// setTimeout(function(){
		// 	msg.filter(function(){
		// 		return $(this).css("display") != "none"; // don't append helper if message is already hidden!
		// 	}).append('<div class="closer_msg"><div class="closer_msg_arrow"></div>Click the message to make it go away.</div>');
		// }, 12000);
	}).attr("title", "Click here to close this message").hover(function(){
		$(this).addClass("hover");
	},function(){
		$(this).removeClass("hover");
	});
	$("div.message, div.message *").livequery(function(){
		$(this).click(hideMessages).css("cursor", "pointer");
	});
	
	// Manipulate breadcrumb navigation.
	$("#breadcrumb").children("a:last").wrap("<span class='breadcrumb current'></span>").each(function(){
		$(this).parent().prepend($(this).text());
	}).remove().end().each(function(){
		if($(this).find("a").length == 0) {
			$(this).children().remove();
		}
	});
	
	// Replace multiple-selects with checkboxMultiples, preserving "selected" status as well 
	$("select").filter(function(){
		return typeof($(this).attr("multiple")) != 'undefined';
	}).each(function(){
		var thisSelect = $(this);
		var id = typeof($(thisSelect).attr("id") != 'undefined') ? ' id="'+$(thisSelect).attr("id")+'"' : '';
		$(thisSelect).after('<ul'+id+' class="checkboxMultiple tags"></ul>');
		$.each($(thisSelect).children("option"), function(i,n){
			var checked = typeof($(n).attr("selected")) != 'undefined' ? ' checked="checked"' : '';
			var inputId = typeof($(thisSelect).attr("id") != 'undefined') ? $(thisSelect).attr("id")+i : '';
			$(thisSelect).next(".checkboxMultiple").append('<li><input id="'+inputId+'" type="checkbox" class="checkbox checkboxMultiple" value="'+$(n).val()+'" name="'+$(thisSelect).attr("name")+'"'+checked+'><label for="'+inputId+'">'+$(n).text()+'</label></li>');
		});
	}).remove();
	
	// First, move all form error messages within the input divs that they apply to, for easier styling.
	// Then, add some clearing divs to make sure the form renders nicely.
	$("#content form div.required, #content form div.optional, #content form div.input").next(".error_message, .error-message").each(function(){
		$(this).prev().append($(this).clone()).end().remove();
	}).end().filter(":last").after("<div class='clear'></div>").end().add($(this).parent()).append("<div class='clear'></div>");
	
	// Orphan? Leftover from cake 1.1 days... 
	// $("#content form div.required, #content form div.optional").children("p.error").each(function(){
	// 	$(this).appendTo($(this).parent());
	// });
	
	// For all required fields, add a star (usually red) indicating that the field is required.
	$("#content form div.required label").append("<span class='required'>*</span>");
	
	// If the form submit div has any secondary form buttons (Cancel, Back, etc.) then move them inside the submit div.
	$("div.submit").each(function(){
		$(this).append($(this).nextAll("a.secondary_form_link")).nextAll("a.secondary_form_link").remove();
	});
	
	// .filter(function(){
	// 	return $(this).next(".secondary_form_link").length != 0;
	// }).css("float", "left");
	
	$("table.listing tr").not(".header").each(function(i){
		if(i%2==0) $(this).addClass("alt");
	});
	
	$("#secondary_tabs").after('<div class="clear"></div>').nextAll("h2").filter(":first").addClass("with_sub_tabs");
	
	
	// ==========================
	// = Attach Global Behavior =
	// ==========================
	
	$("a.delete.confirm").click(function(e){
		return confirm('Are you sure you want to delete this item?');
	});
	
	// Implement rudimentary dropdown menus for CMS navigation
	// alert('hi');
	// $('#navleft').jdMenu();
	// $("#navleft, #navright").children("li").children("a").hover(function(){
	// 	$(this).addClass("hover").next("ul").show();
	// },function(){
	// 	$(this).removeClass("hover").next("ul").hide();
	// }).end().children("ul").hover(function(){
	// 	$(this).show();
	// },function(){
	// 	$(this).prev("a").removeClass("hover").end().hide();
	// }).mousemove(function(){
	// 	$(this).prev("a").addClass("hover").show();
	// });
	
	// Attach behavior to all checkboxMultiples that function as tag choosers.
	$("ul.checkboxMultiple.tags li").children("input[type=checkbox]").each(function(){
		$(this).next("label").each(function(){
			$(this).after('<a id="'+$(this).attr("for")+'_link" class="tag_link" href="#">'+$(this).text()+'</a>').remove();
		}).end().clone(true).insertBefore($(this).parent().parent()).hide().end().each(function(){
			if(this.checked){
				$('#'+this.id+'_link').addClass("checked");
			}
		}).remove();
	}).end().each(function(){
		$(this).children("a.tag_link").click(function(e){
			e.preventDefault();
			var id = this.id.split('_link')[0];
			// alert(id);
			$('input[type=checkbox]').filter('#'+id).each(function(){
				this.checked = this.checked ? false : true;
			});
			$(this).toggleClass('checked');
			this.blur();
		});
	});
	
	// Add extra classes to certain form elements to make CSS styling easier.
	$("input[type=submit], input[type=button], button").livequery(function(){
		$(this).addClass("button");
	});
	$("input[type=submit]").livequery(function(){
		$(this).addClass("submit");
	});
	$("input[type=checkbox]").livequery(function(){
		$(this).addClass("checkbox");
	});
	
	$("input[type=checkbox] + label").livequery(function(){
		$(this).addClass("checkboxLabel");
	});
	
	$("input.publishOption[type=radio] + label").livequery(function(){
		$(this).addClass("radioLabel");
	});
	$("input.publishOption[type=radio]").wrap('<div class="publishOption"></div>').parent().next('label').each(function(){
		$(this).clone(true).appendTo($(this).prev()).end().remove();
	}).end().filter(":first").before('<div class="publishOptionWrap"></div>').end().each(function(){
		$(this).clone(true).appendTo($(this).prevAll(".publishOptionWrap")).end().remove();
	});
	
	$("input[type=text], input[type=password]").livequery(function(){
		$(this).addClass("oneliner");
	});
	$("input[type=text], input[type=password], textarea").livequery(function(){
		$(this).addClass("textbox");
	});
	// $("input[type=text], input[type=password]").addClass("oneliner").add($("textarea")).addClass("textbox");
	
	// $("input, select, textarea, button").filter(function(){
	// 	return this.disabled == true;
	// }).addClass("disabled");
	
	$("input[disabled], select[disabled], textarea[disabled], button[disabled]").livequery(function(){
		$(this).addClass("disabled");
	},function(){
		$(this).removeClass("disabled");
	});
	
	$("input[type=radio]").livequery(function(){
		$(this).addClass("radio");
	});
	
	// Hide all Cake flash messages after a pre-configured interval.
	if(flash_duration > 0){
		setTimeout('hideMessages()', flash_duration);
	}
});

if(typeof(Ext) != 'undefined'){
	Ext.onReady(function(){
		Ext.QuickTips.init();
		Ext.BLANK_IMAGE_URL = webroot+'wwcms/img/s.gif';
	});
}

var preload = function(arrImages){
	$.each(arrImages,function(i,n){
		var img = new Image();
		img.src = webroot + n;
	});
};

var hideMessages = function(){
	$("div.message").filter(function(){
		return $(this).css("display") != "none"; // don't do the fade action if it's already hidden!
	}).each(function(){
		$(this).fadeOut(200);
	});
};

var SessionFlash = function(text, redirect){
	$.ajax({
		type: "GET",
		url: webroot+'admin/pages/sessionFlash/',
		dataType: 'text',
		data: {
			'text': text
		},
		success: function(data, textStatus){
			if(typeof(redirect) != 'undefined'){
				document.location = redirect;
			}
			return true;
		},
		error: function(){
			if(typeof(redirect) != 'undefined'){
				document.location = redirect;
			}
			return false;
		}
	});
};

var AssetFileNameLookup = function(assetId, updateNode){
	var ret = '';
	$.ajax({
		type: "GET",
		url: webroot+'admin/fck/assetFileNameLookup',
		dataType: 'text',
		data: {
			'id': assetId
		},
		success: function(data, textStatus){
			updateNode.val(data);
		},
		error: function(){
			updateNode.val(assetId);
		}
	});
};
// 
// var AssetUrlLookup = function(assetId){
// 	var ret = '';
// 	$.ajax({
// 		type: "GET",
// 		url: webroot+'admin/fck/assetUrlLookup',
// 		dataType: 'text',
// 		data: {
// 			id: assetId
// 		},
// 		success: function(data, textStatus){
// 			ret = data;
// 			return ret;
// 		},
// 		error: function(){
// 			return false;
// 		}
// 	});
// };

var AjaxGetNoReturn = function(url, callback){
	if(url.charAt(0) == '/'){
		url = url.substring(1, url.length-1);
	}
	$.ajax({
		type: "GET",
		url: webroot+url,
		dataType: 'text',
		success: function(data, textStatus){
			if(typeof(callback) == 'function'){
				callback.call(this);
			}
		},
		error: function(){
		}
	});
};

var FCKinit = function(id, options){
	var oFCKeditor = new FCKeditor(id);
	FCKprocessConfig(oFCKeditor, options);
	oFCKeditor.ReplaceTextarea();
};

var FCKprocessConfig = function(fckObj, options){
	$.each(options, function(i,n){
		if(typeof n == 'object'){
			FCKprocessConfig(fckObj[i], n);
		}
		else{
			fckObj[i] = n;
		}
	});
};

var FCKdestroy = function(id){
	$("#"+id+"___Config").nextAll("iframe").andSelf().add($("#"+id)).remove();
};

var scrollbarWidth = 0;
var getScrollbarWidth = function() {
	if (!scrollbarWidth) {
		var testEl = $('<div>')
				.css({
					width: 100,
					height: 100,
					overflow: 'auto',
					position: 'absolute',
					top: -1000,
					left: -1000
				})
				.appendTo('body');
		scrollbarWidth = 100 - testEl
			.append('<div>')
			.find('div')
				.css({
					width: '100%',
					height: 200
				})
				.width();
		testEl.remove();
	}
	return scrollbarWidth;
};

var stringToJson = function(str){
	return eval('(' + str + ')');
};

/* */
/* */

/**
*
* URL encode / decode
* http://www.webtoolkit.info/
*
**/

var Url = {

	// public method for url encoding
	encode : function (string) {
		return escape(this._utf8_encode(string));
	},

	// public method for url decoding
	decode : function (string) {
		return this._utf8_decode(unescape(string));
	},

	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";

		for (var n = 0; n < string.length; n++) {

			var c = string.charCodeAt(n);

			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}

		}

		return utftext;
	},

	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;

		while ( i < utftext.length ) {

			c = utftext.charCodeAt(i);

			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}

		}

		return string;
	}

}
