/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

//common scripts
String.prototype.lpad = function(padString, length) {
	var str = this;
	while (str.length < length)
		str = padString + str;
	return str;
}

//pads right
String.prototype.rpad = function(padString, length) {
	var str = this;
	while (str.length < length)
		str = str + padString;
	return str;
}

String.prototype.ltrim = function () {
	var re = /\s*((\S+\s*)*)/;
	return this.replace(re, "$1");
}

String.prototype.rtrim = function () {
	var re = /((\s*\S+)*)\s*/;
	return this.replace(re, "$1");
}

String.prototype.trim = function () {
	return this.ltrim().rtrim();
}


var Format = {
	arrayToList : function (array, ulClass){
		ulClass = (ulClass) ? ulClass : '';
		var html = '<ul class=' + ulClass + '>';

		for (var i in array)
		{
			html += '<li>' + array[i] + '</li>';
		}

		html += '</ul>';

		return html;
	}
};

var System = {
	root : ''
};

var Window = {
	init : function () {}
}

$(function (){
	Window.init();
});

//dialog box
var Dialog = {
	defaults : {
		type : 'info',
		title : 'Information',
		content : 'Unknown dialogbox call',
		contentList : '',
		events : {
			"Ok" : function () {
				$(this).dialog("close");
			}
		}
	},
	show : function(params) {
		//binf default parameters
		var settings = $.extend(Dialog.defaults, params);

		//generating dialog box html
		if(typeof(settings.contentList) == 'object')
		{
			settings.content = '<ul>';

			for(var i=0; i < settings.contentList.length; i++)
				settings.content += '<li>'+ settings.contentList[i] +'</li>';

			settings.content += '</ul>';
		}
		else if (typeof(settings.contentList) == 'string' && settings.contentList != '')
		{
			settings.content = settings.contentList;
		}

		var id = "dialogbox_" + Math.random(9999);
		var dialogBox = $('<div class="dialog_' + settings.type + '"><div id="' + id + '"><p>' + settings.content + '</p></div></div>');
		var dialogBoxContainer = $('<div style="display:none"></div>');
		dialogBoxContainer.append(dialogBox);

		$("body").append(dialogBoxContainer);

		dialogBox.dialog({
			autoOpen: true,
			width: 600,
			modal: true,
			resizable: false,
			title: settings.title,
			buttons: settings.events
		});
	}
};

var Ajax = {
	defaults : {
		uri : '',
		data : "{}",
		method : 'POST',
		cache : false,
		onSuccess : function (result) {
			var message = (result.message) ? (result.message) : ('Operation completed successfully');

			Dialog.show({
				title : 'Server responce',
				type : 'Information', 
				content : message
			});
		},
		onError : function (errors) {
			Dialog.show({
				title : 'Error',
				type : 'error', 
				contentList : errors
			});
		}
	},
	send : function (options) {
		var settings = $.extend({}, Ajax.defaults, options);

		$.ajax({
			cache: settings.cache,
			type: settings.method,
			url: System.root + settings.uri,
			dataType : 'json',
			data: 'data=' + settings.data,
			success : function (data){
				if(data.errors.length > 0)
					settings.onError(data.errors)
				else
					settings.onSuccess(data.responce);
			},
			error : function (XMLHttpRequest, textStatus, errorThrown) {
				var messageText = '';
				var titleMessage = 'Error responce'

				switch (XMLHttpRequest.status) {
					case 400 :
						titleMessage = 'Bad request 400';
						messageText = '400 - The request had bad syntax or was inherently impossible to be satisfied.';
						break;
					case 401 :
						titleMessage = 'Unauthorized 401';
						messageText = '401 - The parameter to this message gives a specification of authorization schemes which are acceptable. The client should retry the request with a suitable Authorization header.';
						break;
					case 403 :
						titleMessage = 'Forbidden 403';
						messageText = '403 - The request is for something forbidden.';
						break;
					case 404 :
						titleMessage = 'Not found 404';
						messageText = '404 - The server has not found anything matching for the URI given.';
						break;
					case 500 :
						titleMessage = 'Internal Error 500';
						messageText = '500 - The server encountered an unexpected condition which prevented it from fulfilling the request. ';
						break;
					case 200 :
						titleMessage = 'JSON Error';
						messageText = 'Server encountered a json encoding error';
						break;
					default :
						messageText = 'Invalid request [' + XMLHttpRequest.status + ' : ' + XMLHttpRequest.statusText + ']';
				}

				settings.onError([messageText]);
			}
		});
	}
}

var Json = {
	toString : function (object) {
		var jsonString = Json.arrayToString(object, true);
		return jsonString.slice(0,jsonString.length-1);
	},
	arrayToString : function (dataArray, hasKey) {
		var jsonString = hasKey ? '{' : '[';

		for (var key in dataArray)
		{
			var value = dataArray[key];

			if($.isArray(value))
			{
				if (isNaN(key))
					jsonString += '"' + key + '":' +  Json.arrayToString(value, ($.isArray(value) && value[0] == null));
				else
					jsonString +=  Json.arrayToString(value, ($.isArray(value) && value[0] == null));
			}
			else if (typeof (value) == 'object')
			{
				if (isNaN(key))
					jsonString += '"' + key + '":' +  Json.arrayToString(value, true);
				else
					jsonString +=  Json.arrayToString(value, false);
			}
			else
			{
				if (isNaN(key))
					jsonString += '"' + key + '":"' + Json.escape(value) + '",';
				else
					jsonString += '"' + Json.escape(value) + '",';
			}
		}

		if(jsonString.length > 1)
            jsonString = jsonString.slice(0,jsonString.length-1);

        jsonString += hasKey ? '},' : '],';

        return jsonString;
	},
	escape : function (string){
		string = string.replace(/\\/g, '\\/');
		string = string.replace(/\"/g,'\\"');
		string = string.replace(/&/g, '#amp;');
		string = string.replace(/(\r\n|\n|\r)/gm,"<br />");
		string = string.replace(/\t/gm,"");

		string = encodeURIComponent(string);

		return string;
	},
	stringToObject : function (string){
		var val = {};
		string = "val = " + string;
		eval (string);

		return val;
	}
};

$.fn.form = function (options){
	return $(this).each(function () {
		var form = new Form($(this), options);
		form.constructor();
	});
};

var Form = function (object, options){
	var self = this;
	var target  = object;
	var defaults = {
		action : '',
		method : 'POST',
		type : 'AJAX',
		showLoading : true,
		onSuccess : function (result) {
			var message = (result.message) ? (result.message) : ('Operation completed successfully');

			Dialog.show({
				title : 'Server responce',
				type : 'Information',
				content : message
			});
		},
		onError : function (errors) {
			Dialog.show({
				title : 'Error',
				type : 'error',
				contentList : errors
			});
		}
	};
	var settings = $.extend(defaults, options);

	this.constructor = function () {
		//this.fetchFormInfo();
		this.setButtonActions();
	}

//	this.fetchFormInfo = function() {
//		var config = {};
//		$('.settings div', target).each(function () {
//			var param = $(this);
//			config[param.attr('class')] = param.html().replace(/&amp;/gi, '&');
//		})
//
//		settings = $.extend(settings, config);
//	}

	this.setButtonActions = function ()
	{
		$(".submit", target).not($(".form-panel .submit", target)).click(function () {
			self.submit();
		});

		$(".clear", target).not($(".form-panel .clear", target)).click(function () {
			self.clear();
		});
	}

	this.clear = function () {
		$("input", target).each(function () {
			var self = $(this);
			if (this.type == 'text')
				self.val('');
		});
		$("select", target).val('');
		$("textarea", target).val('');
		try
		{
			$("textarea", target).wysiwyg('setContent', '');
		}
		catch (e)
		{
			
		}
	}

	this.submit = function (){
		var dataSet = self.getFormVars();
		var post = '{"' + target.attr('id') + '":' +  Json.toString(dataSet) + "}";
		Ajax.send({
			uri : settings.action,
			data : post,
			method : settings.method,
			onSuccess : settings.onSuccess,
			onError : settings.onError
		});
	}

	this.getFormVars = function (panel)
	{
		panel = (panel) ? panel : target;

		var dataArray = Array();

		//read main panel
		$("input", panel).not($('.form-panel input', panel)).each(function (i, inputBox) {

			if (inputBox.type == 'checkbox')
			{
				if (inputBox.checked)
				{
					if (dataArray[inputBox.name] == null)
						dataArray[inputBox.name] = Array();

					dataArray[inputBox.name].push(inputBox.value);
				}
			}
			else if (inputBox.type == 'radio')
			{
				if (inputBox.checked)
				{
					dataArray[inputBox.name] = inputBox.value;
				}
			}
			else
			{
				dataArray[inputBox.name] = inputBox.value;
			}
		});

		$("select", panel).not($('.form-panel select', panel)).each(function (i, selectBox) {
			var name = selectBox.name;

			$(":selected", selectBox).each(function (i, selectedOption)
			{
				if ($(selectBox).attr('multiple'))
				{
					if (dataArray[name] == null)
						dataArray[name] = Array();

					dataArray[name].push(selectedOption.value);
				}
				else
				{
					dataArray[name] = selectedOption.value;
				}
			});
		});

		$("textarea", panel).not($('.form-panel textarea', panel)).each(function (i, textarea) {
			dataArray[textarea.name] = textarea.value;
		});

		//read sub panels
		var subPanels = $(".form-panel", panel).not($(".form-panel .form-panel", panel));

		if (subPanels.length > 0)
		{
			dataArray['sub_panels'] = Array();
			$(subPanels).each(function (i, subPanel) {
				dataArray['sub_panels'].push(self.getFormVars(subPanel));
			});
		}

		return dataArray;
	}
}



$(function () {

	try
{
	$("a.fancybox").fancybox({
			'titleShow'     : false,
			'transitionIn'  : 'elastic',
			'transitionOut' : 'elastic',
			'autoScale'		: true,
			'href' : $("a.fancybox").attr('href').replace(new RegExp("watch\\?v=", "i"), 'v/'),
			'type'      : 'swf',
			'swf'       : {'wmode':'transparent','allowfullscreen':'true'}
		});
}
catch (e)
{

}
});

