// JavaScript Document
/* Global Storage Object */
var Global = {};
/* Global Functions */
function gid( id )
{
	return document.getElementById( id );
}
Global.GetTempId = function( attachString ){
	attachString = attachString || "tempobj";
	var itr = 0;
	while( gid( attachString + itr ) ){
		itr++;
	}
	
	return attachString + itr;
}

/**
 * XTends a set of html to use a UI
 *
 * @param HTMLElement object
 *	The starting html element to search using jQuery
 *
 * @author Stev0 <alexdragin@gmail.com>
 */
function objXTend( ){
/////////////////Private Methods/////////////////
	/**
	 * Complies a string into a NoS object
	 *
	 * @param string string
	 *	The string to turn into a NoS object
	 * @return object
	 *	NoS object { key, vars:{ } };
	 *
	 * @author Stev0 <alexdragin@gmail.com>
	 */
	function CompileNoS( string ){
		string = string.replace( /`/g, "\"" );
		var keystr, varobj = "";
		if( string.search( /\{/g ) != - 1 ){
			keystr = string.substr( 0, string.search( /\{/g ) );
		}
		else{
			keystr = string;
		}
		varobj = string.substr( keystr.length );
		if( varobj == "" )
			varobj = "{ }";
		try{
		eval( "varobj = " + varobj + ";" );
		}catch( error ){ alert( "Error with the evaluation\n\n" + "varobj = " + varobj + ";\n\n" + error ); }
		return { key:keystr, vars:varobj };
	}
	/**
	 * Compiles the elements into xwidgets, removing the need to always use the xwigdet syntax
	 * @param obj
	 * 	The object that will have the attribute compiled
	 * @param type
	 * @return
	 */
	function CompileAttr( obj, type ){
		if( !$(obj).attr( "xwidget" ) || $(obj).attr( "xwidget" ) == "" )
			$(obj).attr( "xwidget", type );
		else if( $(obj).attr( "xwidget" ).substr( 0, type.length ) != type &&
			( $(obj).attr( "xwidget" ).search( /\{/ ) == -1 || $.trim( $(obj).attr( "xwidget" ) ).search( /\{/ ) == 0 ) ){
			$(obj).attr( "xwidget", type + $(obj).attr( "xwidget" ) );
		}
	}
	/**
	 * Creates the results of the search with self included
	 * @param searchString
	 * @param excludeSelf
	 * @param object
	 * @return
	 */
	function CreateSearch( searchString, excludeSelf, object ){
		var search = $( searchString, object );
		return search = ( ( !excludeSelf && $( object ).is( searchString ) ) ? search.add( object ) : search );
	}
	/**
	 * Method that applies 
	 * @param startingExtention
	 * @return int of the first extention in the next group
	 */
	function ApplyExtentions( extentionList, object, excludeSelf, parentXObject ){
		excludeSelf = excludeSelf || false;
		for( var __i = 0; __i < extentionList.length; __i++ ){
			switch( extentionList[__i].type ){
				case "search":
					$( extentionList[__i].search, object ).each( function( i ){
						this.__xtendMethod = extentionList[__i].method;
						this.__xtendMethod( object, parentXObject, i );
						this.__xtendMethod = null;
					} );
					break;
				case "compile":
					CreateSearch( extentionList[__i].search, excludeSelf, object ).each( function( i ){
						CompileAttr( this, extentionList[__i].settings.compileName );
						this.__xtendMethod = extentionList[__i].method;
						this.__xtendMethod( object, parentXObject, i );
						this.__xtendMethod = null;
					} );
					break;
				default:
					alert( "Error unknown type of extention!" );
					break;
			}
		}
	}
////////////////Private Variables////////////////
	/**
	 * The extention list
	 */
	var preExtentions = [];
	/**
	 * The extention list that is run after the xwidgets
	 */
	var postExtentions = [];
	/**
	 * The xwidget list
	 */
	var xwidgets = {};
/////////////////Public Methods//////////////////
	/**
	 * Adds the extention to the list of extentions
	 */
	this.AddExtention = function( type, searchString, eachMethod, settings, afterWidgets ){
		eachMethod = eachMethod || function(){};
		afterWidgets = afterWidgets || false;
		settings = settings || {};
		if( !afterWidgets ){
			preExtentions.push( { type:type, search:searchString, method:eachMethod, settings:settings } );
		}
		else{
			postExtentions.push( { type:type, search:searchString, method:eachMethod, settings:settings } );
		}
	};
	/**
	 * @see AddExtention
	 */
	this.AddExtentions = function( type, exts, afterWidgets ){
		afterWidgets = afterWidgets || false;
		for( var i = 0; i < exts.length; i++ ){
			exts[i].method = exts[i].method || function(){};
			exts[i].settings = exts[i].settings || { };
			XTend.AddExtention( type, exts[i].search, exts[i].method, exts[i].settings, afterWidgets );
		}
	};
	/**
	 * Adds an xWidget to the list of xwidgets
	 */
	this.AddXWidget = function( name, method ){
		xwidgets[name] = method;
	};
	/**
	 * Adds an array of xWidget to the list of xwidgets
	 */
	this.AddXWidgets = function( xwigs ){
		for( var i = 0; i < xwigs.length; i++ ){
			this.AddXWidget( xwigs[i].name, xwigs[i].method );
		}
	};
	/**
	 * Applies the extentions to the object in question
	 */
	this.ApplyToObject = function( object, parentXObject, excludeSelf ){
		parentXObject = parentXObject || null;
		excludeSelf = excludeSelf || false;
		if( parentXObject != null && !parentXObject.element && !parentXObject.que ){
			parentXObject.ajax_que = parentXObject.ajax_que || new Array();
			parentXObject = { element:object, que:parentXObject.ajax_que };
		}
		else{
			if( parentXObject != null && !parentXObject.element || parentXObject != null && !parentXObject.que ){
				alert( "Error parent XObject incompleate\nElement: " + parentXObject.element + "\nQue: " + parentXObject.que );
			}
		}
		ApplyExtentions( preExtentions, object, excludeSelf, parentXObject );
		CreateSearch( "*[xwidget]", excludeSelf, object ).each( function( i ){
			var self = this;
			this.__compileNoS = CompileNoS;
			var xwc = this.__compileNoS( $(this).attr( "xwidget" ) );
			if( xwidgets[xwc.key] ){
				if( !$(this).attr( "id" ) ){
					$(this).attr( "id", Global.GetTempId( xwc.key ) );
				}
				this.__xtendMethod = xwidgets[xwc.key];
				this.__xtendMethod( xwc.vars, object, parentXObject, i );
				this.__xtendMethod = null;
			}
			else{
				alert( "Error 904:\nXWidget method for " + xwc.key + " not found!" );
			}
		} );
		ApplyExtentions( postExtentions, object, excludeSelf, parentXObject );
	};
}var XTend = new objXTend();

//MUST BE FIRST BECAUSE IT COULD CONTAIN HTML AND WE DON'T NEED TO LOAD IT TWICE
XTend.AddExtention( 'compile', "[nodechange='dialog']", function( ){
	this.refHtml = $(this).html();
	$(this).html( "Loading XWidget..." );
}, { compileName:"dialog" } );
//MUST BE FIRST BECAUSE IT COULD CONTAIN HTML AND WE DON'T NEED TO LOAD IT TWICE
XTend.AddExtentions( 'search', [ {
			search:"*[onmouseenter]", 
			method:function(){
				$(this).bind( "mouseenter", function( e ){ eval( $(this).attr( "onmouseenter" ) ) } );
			}
		}, {
			search:"*[onmouseleave]",
			method:function(){
				$(this).bind( "mouseleave", function( e ){ eval( $(this).attr( "onmouseleave" ) ) } );
			}
		}
] );
XTend.AddExtention( 'search', "*[onmouseleave]", function(){
	$(this).bind( "mouseleave", function( e ){ eval( $(this).attr( "onmouseleave" ) ) } );
} );
XTend.AddExtentions( 'compile', [ {
			search:"button, input:button, input:submit",
			method:function(){
				if( this.nodeName.toLowerCase() == "button" ){
					var text = $(this).attr( "value" ) || $(this).attr( "label" ) || $(this).attr( "text" );
					$(this).append( text );
				}
			},
			settings:{ compileName:"button" }
		},{
			search:"tabpane",
			settings:{ compileName: "tabpane" }
		},{
			search:"input:text, textarea, input:password",
			settings:{ compileName: "textbox" }
		}
] );

XTend.AddXWidgets( 
	[ {
	 	name:"servermsg",
		method:function( params ){
			$(this).hide().html( ServerOutput[params.msg] );
			if( params.fade ){
				$(this).fadeIn( 2500, function(){
					var me = this;
					setTimeout( function(){ $(me).fadeOut( 2500 ) }, 5000 );
				} );
			}
			else{
				$(this).show();
			}
		}
	}, { 
		name:"ajaxfile",
		method:function( params ){
			var xtendself = this;
			var button = $('<input type="button" value="upload" />');
			button.bind( "click", function(){
				alert( $(xtendself).attr( "id" ) );
				$.ajaxFileUpload
				(
					{
						url:'../../lib/ajaxupload.php',
						secureuri:false,
						fileElementId:$(xtendself).attr( "id" ),
						dataType: 'json',
						data:"type="+params.dataType,
						success: function (data, status)
						{
							if(typeof(data.error) != 'undefined')
							{
								if(data.error != '')
								{
									alert(data.error);
								}else
								{
									alert(data.msg);
								}
							}
						},
						error: function (data, status, e)
						{
							alert(e);
						},
						complete: function( result, status ){
							alert( result.responseText );
						}
					}
				)
			} );
			$(this).after( button );
		}
	}, { 
		name:"combobox",
		method:function( params ){
			$(this).combobox( params );
		}
	}, { 
		name:"tabpane",
		method:function( params ){
			$(this).addClass( "tabbox" );
			params.selected = params.selected || 0;
			$(this).tabs( params );
		}
	}, {
		name:"textbox",
		method:function( params ){
			$(this).addClass( "ui-widget ui-widget-content" );
		}
	}, {
		name:"blackout",
		method:function( params ){
			if( params.isBlackedOut ){
				$(this).css( { 'background-color':"#000000" } );
			}
			else{
				$(this).bind( "mouseenter", function(){
					$(this).css( 'background-color', '#333333' ).append( "<div xid='blackout' style='background-color:#000000;position:absolute;border:solid 1px #777777;'>Click to blackout date.</div>" );
				} );
				$(this).bind( "mouseleave", function(){
					$(this).css( 'background-color', '' );
					$( "*[xid='blackout']", this ).remove();
				} );
				$(this).bind( "click", function(){
					//$(this).
				} );
			}
		}
	}, {
		name:"textboxdatebox",
		method:function( params ){
			$(this).datepicker( params );
		}
	},{
		name:"hldiv",
		method:function( params ){
			var self = this;
			$(this).css( { "padding":"3px" } );
			$(this).hover(
				function(){
					$(this).addClass( "ui-state-background-highlight" );
				},
				function(){
					$(this).removeClass( "ui-state-background-highlight" );
				}
			);
		}
	},{
		name:"button",
		method:function( params ){
			$(this).button( params );
		}
	},{
		name:"buttonset",
		method:function( params ){
			$(this).buttonset( );
		}
	},{
		name:"dialog",
		method:function( params ){
			$(this).html( this.refHtml );
			params.autoOpen = params.autoOpen || false;
			params.buttons = params.buttons || {};
			var buttonArray = [];
			$( "dlgbutton", this ).each( function(){
				buttonArray.push( this );
			} );
			for( var i = buttonArray.length; i > 0; i-- ){
				var btn = buttonArray[i-1];
				var buttonName = $(btn).attr( "value" ) || "U";
				if( $.browser.msie )
					eval( 'params.buttons[buttonName] = function(){ ' + btn.onclick + ' };' );
				else
					params.buttons[buttonName] = btn.onclick;
				$(btn).remove();
			}
			
			buttonArray.length = 0;
			$(this).html( '<div style="padding-left:10px;padding-right:10px;">' + $(this).html() + "</div>" );
			XTend.ApplyToObject( this, null, true );
			try{
				$(this).dialog( params );
			}catch( ex ){
				
			}
		}
	}
] );

/*
		
		$( "[tooltip]", object ).each( function( i ){
			$(this).attr( "title", $(this).attr( "tooltip" ) );
			$(this).tooltip( {
				position: "center right",
				effect: 'slide',
				slideOffset: 30,
				opacity: 0.85
			} );
		} );
	}*/

function AjaxUpload( id, data ){
	data = data || "type=test";
	$.ajaxFileUpload
	(
		{
			url:'../../lib/ajaxupload.php',
			secureuri:false,
			fileElementId:id,
			dataType: 'json',
			data:data,
			success: function (data, status)
			{
				if(typeof(data.error) != 'undefined')
				{
					if(data.error != '')
					{
						alert(data.error);
					}else
					{
						alert(data.msg);
					}
				}
			},
			error: function (data, status, e)
			{
				alert(e);
			}
		}
	)
	
	return false;

}



/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
