

/*!
 * jQuery Form Plugin
 * version: 2.80 (25-MAY-2011)
 * @requires jQuery v1.3.2 or later
 *
 * Examples and documentation at: http://malsup.com/jquery/form/
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */
;(function($) {

/*
	Usage Note:
	-----------
	Do not use both ajaxSubmit and ajaxForm on the same form.  These
	functions are intended to be exclusive.  Use ajaxSubmit if you want
	to bind your own submit handler to the form.  For example,

	$(document).ready(function() {
		$('#myForm').bind('submit', function(e) {
			e.preventDefault(); // <-- important
			$(this).ajaxSubmit({
				target: '#output'
			});
		});
	});

	Use ajaxForm when you want the plugin to manage all the event binding
	for you.  For example,

	$(document).ready(function() {
		$('#myForm').ajaxForm({
			target: '#output'
		});
	});

	When using ajaxForm, the ajaxSubmit function will be invoked for you
	at the appropriate time.
*/

/**
 * ajaxSubmit() provides a mechanism for immediately submitting
 * an HTML form using AJAX.
 */
$.fn.ajaxSubmit = function(options) {
	// fast fail if nothing selected (http://dev.jquery.com/ticket/2752)
	if(this == undefined){
		return false;
	}
	
	if (!this.length) {
		log('ajaxSubmit: skipping submit process - no element selected');
		return this;
	}

	if (typeof options == 'function') {
		options = { success: options };
	}

	var action = this.attr('action');
	var url = (typeof action === 'string') ? $.trim(action) : '';
	url = url || window.location.href || '';
	if (url) {
		// clean url (don't include hash vaue)
		url = (url.match(/^([^#]+)/)||[])[1];
	}

	options = $.extend(true, {
		url:  url,
		success: $.ajaxSettings.success,
		type: this[0].getAttribute('method') || 'GET', // IE7 massage (see issue 57)
		iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank'
	}, options);

	// hook for manipulating the form data before it is extracted;
	// convenient for use with rich editors like tinyMCE or FCKEditor
	var veto = {};
	this.trigger('form-pre-serialize', [this, options, veto]);
	if (veto.veto) {
		log('ajaxSubmit: submit vetoed via form-pre-serialize trigger');
		return this;
	}

	// provide opportunity to alter form data before it is serialized
	if (options.beforeSerialize && options.beforeSerialize(this, options) === false) {
		log('ajaxSubmit: submit aborted via beforeSerialize callback');
		return this;
	}

	var n,v,a = this.formToArray(options.semantic);
	if (options.data) {
		options.extraData = options.data;
		for (n in options.data) {
			if(options.data[n] instanceof Array) {
				for (var k in options.data[n]) {
					a.push( { name: n, value: options.data[n][k] } );
				}
			}
			else {
				v = options.data[n];
				v = $.isFunction(v) ? v() : v; // if value is fn, invoke it
				a.push( { name: n, value: v } );
			}
		}
	}

	// give pre-submit callback an opportunity to abort the submit
	if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) {
		log('ajaxSubmit: submit aborted via beforeSubmit callback');
		return this;
	}

	// fire vetoable 'validate' event
	this.trigger('form-submit-validate', [a, this, options, veto]);
	if (veto.veto) {
		log('ajaxSubmit: submit vetoed via form-submit-validate trigger');
		return this;
	}

	var q = $.param(a);

	if (options.type.toUpperCase() == 'GET') {
		options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q;
		options.data = null;  // data is null for 'get'
	}
	else {
		options.data = q; // data is the query string for 'post'
	}

	var $form = this, callbacks = [];
	if (options.resetForm) {
		callbacks.push(function() { $form.resetForm(); });
	}
	if (options.clearForm) {
		callbacks.push(function() { $form.clearForm(); });
	}

	// perform a load on the target only if dataType is not provided
	if (!options.dataType && options.target) {
		var oldSuccess = options.success || function(){};
		callbacks.push(function(data) {
			var fn = options.replaceTarget ? 'replaceWith' : 'html';
			$(options.target)[fn](data).each(oldSuccess, arguments);
		});
	}
	else if (options.success) {
		callbacks.push(options.success);
	}

	options.success = function(data, status, xhr) { // jQuery 1.4+ passes xhr as 3rd arg
		var context = options.context || options;   // jQuery 1.4+ supports scope context 
		for (var i=0, max=callbacks.length; i < max; i++) {
			callbacks[i].apply(context, [data, status, xhr || $form, $form]);
		}
	};

	// are there files to upload?
	var fileInputs = $('input:file', this).length > 0;
	var mp = 'multipart/form-data';
	var multipart = ($form.attr('enctype') == mp || $form.attr('encoding') == mp);

	// options.iframe allows user to force iframe mode
	// 06-NOV-09: now defaulting to iframe mode if file input is detected
   if (options.iframe !== false && (fileInputs || options.iframe || multipart)) {
	   // hack to fix Safari hang (thanks to Tim Molendijk for this)
	   // see:  http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d
	   if (options.closeKeepAlive) {
		   $.get(options.closeKeepAlive, function() { fileUpload(a); });
		}
	   else {
		   fileUpload(a);
		}
   }
   else {
		$.ajax(options);
   }

	// fire 'notify' event
	this.trigger('form-submit-notify', [this, options]);
	return this;


	// private function for handling file uploads (hat tip to YAHOO!)
	function fileUpload(a) {
		var form = $form[0], i, s, g, id, $io, io, xhr, sub, n, timedOut, timeoutHandle;

        if (a) {
        	// ensure that every serialized input is still enabled
          	for (i=0; i < a.length; i++) {
            	$(form[a[i].name]).attr('disabled', false);
          	}
        }

		if ($(':input[name=submit],:input[id=submit]', form).length) {
			// if there is an input with a name or id of 'submit' then we won't be
			// able to invoke the submit fn on the form (at least not x-browser)
			alert('Error: Form elements must not have name or id of "submit".');
			return;
		}
		
		s = $.extend(true, {}, $.ajaxSettings, options);
		s.context = s.context || s;
		id = 'jqFormIO' + (new Date().getTime());
		if (s.iframeTarget) {
			$io = $(s.iframeTarget);
			n = $io.attr('name');
			if (n == null)
			 	$io.attr('name', id);
			else
				id = n;
		}
		else {
			$io = $('<iframe name="' + id + '" src="'+ s.iframeSrc +'" />');
			$io.css({ position: 'absolute', top: '-1000px', left: '-1000px' });
		}
		io = $io[0];


		xhr = { // mock object
			aborted: 0,
			responseText: null,
			responseXML: null,
			status: 0,
			statusText: 'n/a',
			getAllResponseHeaders: function() {},
			getResponseHeader: function() {},
			setRequestHeader: function() {},
			abort: function(status) {
				var e = (status === 'timeout' ? 'timeout' : 'aborted');
				log('aborting upload... ' + e);
				this.aborted = 1;
				$io.attr('src', s.iframeSrc); // abort op in progress
				xhr.error = e;
				s.error && s.error.call(s.context, xhr, e, e);
				g && $.event.trigger("ajaxError", [xhr, s, e]);
				s.complete && s.complete.call(s.context, xhr, e);
			}
		};

		g = s.global;
		// trigger ajax global events so that activity/block indicators work like normal
		if (g && ! $.active++) {
			$.event.trigger("ajaxStart");
		}
		if (g) {
			$.event.trigger("ajaxSend", [xhr, s]);
		}

		if (s.beforeSend && s.beforeSend.call(s.context, xhr, s) === false) {
			if (s.global) {
				$.active--;
			}
			return;
		}
		if (xhr.aborted) {
			return;
		}

		// add submitting element to data if we know it
		sub = form.clk;
		if (sub) {
			n = sub.name;
			if (n && !sub.disabled) {
				s.extraData = s.extraData || {};
				s.extraData[n] = sub.value;
				if (sub.type == "image") {
					s.extraData[n+'.x'] = form.clk_x;
					s.extraData[n+'.y'] = form.clk_y;
				}
			}
		}

		// take a breath so that pending repaints get some cpu time before the upload starts
		function doSubmit() {
			// make sure form attrs are set
			var t = $form.attr('target'), a = $form.attr('action');

			// update form attrs in IE friendly way
			form.setAttribute('target',id);
			if (form.getAttribute('method') != 'POST') {
				form.setAttribute('method', 'POST');
			}
			if (form.getAttribute('action') != s.url) {
				form.setAttribute('action', s.url);
			}

			// ie borks in some cases when setting encoding
			if (! s.skipEncodingOverride) {
				$form.attr({
					encoding: 'multipart/form-data',
					enctype:  'multipart/form-data'
				});
			}

			// support timout
			if (s.timeout) {
				timeoutHandle = setTimeout(function() { timedOut = true; cb(true); }, s.timeout);
			}

			// add "extra" data to form if provided in options
			var extraInputs = [];
			try {
				if (s.extraData) {
					for (var n in s.extraData) {
						extraInputs.push(
							$('<input type="hidden" name="'+n+'" value="'+s.extraData[n]+'" />')
								.appendTo(form)[0]);
					}
				}

				if (!s.iframeTarget) {
					// add iframe to doc and submit the form
					$io.appendTo('body');
	                io.attachEvent ? io.attachEvent('onload', cb) : io.addEventListener('load', cb, false);
				}
				form.submit();
			}
			finally {
				// reset attrs and remove "extra" input elements
				form.setAttribute('action',a);
				if(t) {
					form.setAttribute('target', t);
				} else {
					$form.removeAttr('target');
				}
				$(extraInputs).remove();
			}
		}

		if (s.forceSync) {
			doSubmit();
		}
		else {
			setTimeout(doSubmit, 10); // this lets dom updates render
		}

		var data, doc, domCheckCount = 50, callbackProcessed;

		function cb(e) {
			if (xhr.aborted || callbackProcessed) {
				return;
			}
			if (e === true && xhr) {
				xhr.abort('timeout');
				return;
			}

			var doc = io.contentWindow ? io.contentWindow.document : io.contentDocument ? io.contentDocument : io.document;
			if (!doc || doc.location.href == s.iframeSrc) {
				// response not received yet
				if (!timedOut)
					return;
			}
            io.detachEvent ? io.detachEvent('onload', cb) : io.removeEventListener('load', cb, false);

			var status = 'success', errMsg;
			try {
				if (timedOut) {
					throw 'timeout';
				}

				var isXml = s.dataType == 'xml' || doc.XMLDocument || $.isXMLDoc(doc);
				log('isXml='+isXml);
				if (!isXml && window.opera && (doc.body == null || doc.body.innerHTML == '')) {
					if (--domCheckCount) {
						// in some browsers (Opera) the iframe DOM is not always traversable when
						// the onload callback fires, so we loop a bit to accommodate
						log('requeing onLoad callback, DOM not available');
						setTimeout(cb, 250);
						return;
					}
					// let this fall through because server response could be an empty document
					//log('Could not access iframe DOM after mutiple tries.');
					//throw 'DOMException: not available';
				}

				//log('response detected');
                var docRoot = doc.body ? doc.body : doc.documentElement;
                xhr.responseText = docRoot ? docRoot.innerHTML : null;
				xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc;
				if (isXml)
					s.dataType = 'xml';
				xhr.getResponseHeader = function(header){
					var headers = {'content-type': s.dataType};
					return headers[header];
				};
                // support for XHR 'status' & 'statusText' emulation :
                if (docRoot) {
                    xhr.status = Number( docRoot.getAttribute('status') ) || xhr.status;
                    xhr.statusText = docRoot.getAttribute('statusText') || xhr.statusText;
                }

				var dt = s.dataType || '';
				var scr = /(json|script|text)/.test(dt.toLowerCase());
				if (scr || s.textarea) {
					// see if user embedded response in textarea
					var ta = doc.getElementsByTagName('textarea')[0];
					if (ta) {
						xhr.responseText = ta.value;
                        // support for XHR 'status' & 'statusText' emulation :
                        xhr.status = Number( ta.getAttribute('status') ) || xhr.status;
                        xhr.statusText = ta.getAttribute('statusText') || xhr.statusText;
					}
					else if (scr) {
						// account for browsers injecting pre around json response
						var pre = doc.getElementsByTagName('pre')[0];
						var b = doc.getElementsByTagName('body')[0];
						if (pre) {
							xhr.responseText = pre.textContent ? pre.textContent : pre.innerHTML;
						}
						else if (b) {
							xhr.responseText = b.innerHTML;
						}
					}
				}
				else if (s.dataType == 'xml' && !xhr.responseXML && xhr.responseText != null) {
					xhr.responseXML = toXml(xhr.responseText);
				}

                try {
                    data = httpData(xhr, s.dataType, s);
                }
                catch (e) {
                    status = 'parsererror';
                    xhr.error = errMsg = (e || status);
                }
			}
			catch (e) {
				log('error caught',e);
				status = 'error';
                xhr.error = errMsg = (e || status);
			}

			if (xhr.aborted) {
				log('upload aborted');
				status = null;
			}

            if (xhr.status) { // we've set xhr.status
                status = (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) ? 'success' : 'error';
            }

			// ordering of these callbacks/triggers is odd, but that's how $.ajax does it
			if (status === 'success') {
				s.success && s.success.call(s.context, data, 'success', xhr);
				g && $.event.trigger("ajaxSuccess", [xhr, s]);
			}
            else if (status) {
				if (errMsg == undefined)
					errMsg = xhr.statusText;
				s.error && s.error.call(s.context, xhr, status, errMsg);
				g && $.event.trigger("ajaxError", [xhr, s, errMsg]);
            }

			g && $.event.trigger("ajaxComplete", [xhr, s]);

			if (g && ! --$.active) {
				$.event.trigger("ajaxStop");
			}

			s.complete && s.complete.call(s.context, xhr, status);

			callbackProcessed = true;
			if (s.timeout)
				clearTimeout(timeoutHandle);

			// clean up
			setTimeout(function() {
				if (!s.iframeTarget)
					$io.remove();
				xhr.responseXML = null;
			}, 100);
		}

		var toXml = $.parseXML || function(s, doc) { // use parseXML if available (jQuery 1.5+)
			if (window.ActiveXObject) {
				doc = new ActiveXObject('Microsoft.XMLDOM');
				doc.async = 'false';
				doc.loadXML(s);
			}
			else {
				doc = (new DOMParser()).parseFromString(s, 'text/xml');
			}
			return (doc && doc.documentElement && doc.documentElement.nodeName != 'parsererror') ? doc : null;
		};
		var parseJSON = $.parseJSON || function(s) {
			return window['eval']('(' + s + ')');
		};

		var httpData = function( xhr, type, s ) { // mostly lifted from jq1.4.4

			var ct = xhr.getResponseHeader('content-type') || '',
				xml = type === 'xml' || !type && ct.indexOf('xml') >= 0,
				data = xml ? xhr.responseXML : xhr.responseText;

			if (xml && data.documentElement.nodeName === 'parsererror') {
				$.error && $.error('parsererror');
			}
			if (s && s.dataFilter) {
				data = s.dataFilter(data, type);
			}
			if (typeof data === 'string') {
				if (type === 'json' || !type && ct.indexOf('json') >= 0) {
					data = parseJSON(data);
				} else if (type === "script" || !type && ct.indexOf("javascript") >= 0) {
					$.globalEval(data);
				}
			}
			return data;
		};
	}
};

/**
 * ajaxForm() provides a mechanism for fully automating form submission.
 *
 * The advantages of using this method instead of ajaxSubmit() are:
 *
 * 1: This method will include coordinates for <input type="image" /> elements (if the element
 *	is used to submit the form).
 * 2. This method will include the submit element's name/value data (for the element that was
 *	used to submit the form).
 * 3. This method binds the submit() method to the form for you.
 *
 * The options argument for ajaxForm works exactly as it does for ajaxSubmit.  ajaxForm merely
 * passes the options argument along after properly binding events for submit elements and
 * the form itself.
 */
$.fn.ajaxForm = function(options) {
	// in jQuery 1.3+ we can fix mistakes with the ready state
	if (this.length === 0) {
		var o = { s: this.selector, c: this.context };
		if (!$.isReady && o.s) {
			log('DOM not ready, queuing ajaxForm');
			$(function() {
				$(o.s,o.c).ajaxForm(options);
			});
			return this;
		}
		// is your DOM ready?  http://docs.jquery.com/Tutorials:Introducing_$(document).ready()
		log('terminating; zero elements found by selector' + ($.isReady ? '' : ' (DOM not ready)'));
		return this;
	}

	return this.ajaxFormUnbind().bind('submit.form-plugin', function(e) {
		if (!e.isDefaultPrevented()) { // if event has been canceled, don't proceed
			e.preventDefault();
			$(this).ajaxSubmit(options);
		}
	}).bind('click.form-plugin', function(e) {
		var target = e.target;
		var $el = $(target);
		if (!($el.is(":submit,input:image"))) {
			// is this a child element of the submit el?  (ex: a span within a button)
			var t = $el.closest(':submit');
			if (t.length == 0) {
				return;
			}
			target = t[0];
		}
		var form = this;
		form.clk = target;
		if (target.type == 'image') {
			if (e.offsetX != undefined) {
				form.clk_x = e.offsetX;
				form.clk_y = e.offsetY;
			} else if (typeof $.fn.offset == 'function') { // try to use dimensions plugin
				var offset = $el.offset();
				form.clk_x = e.pageX - offset.left;
				form.clk_y = e.pageY - offset.top;
			} else {
				form.clk_x = e.pageX - target.offsetLeft;
				form.clk_y = e.pageY - target.offsetTop;
			}
		}
		// clear form vars
		setTimeout(function() { form.clk = form.clk_x = form.clk_y = null; }, 100);
	});
};

// ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm
$.fn.ajaxFormUnbind = function() {
	return this.unbind('submit.form-plugin click.form-plugin');
};

/**
 * formToArray() gathers form element data into an array of objects that can
 * be passed to any of the following ajax functions: $.get, $.post, or load.
 * Each object in the array has both a 'name' and 'value' property.  An example of
 * an array for a simple login form might be:
 *
 * [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]
 *
 * It is this array that is passed to pre-submit callback functions provided to the
 * ajaxSubmit() and ajaxForm() methods.
 */
$.fn.formToArray = function(semantic) {
	var a = [];
	if (this.length === 0) {
		return a;
	}

	var form = this[0];
	var els = semantic ? form.getElementsByTagName('*') : form.elements;
	if (!els) {
		return a;
	}

	var i,j,n,v,el,max,jmax;
	for(i=0, max=els.length; i < max; i++) {
		el = els[i];
		n = el.name;
		if (!n) {
			continue;
		}

		if (semantic && form.clk && el.type == "image") {
			// handle image inputs on the fly when semantic == true
			if(!el.disabled && form.clk == el) {
				a.push({name: n, value: $(el).val()});
				a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
			}
			continue;
		}

		v = $.fieldValue(el, true);
		if (v && v.constructor == Array) {
			for(j=0, jmax=v.length; j < jmax; j++) {
				a.push({name: n, value: v[j]});
			}
		}
		else if (v !== null && typeof v != 'undefined') {
			a.push({name: n, value: v});
		}
	}

	if (!semantic && form.clk) {
		// input type=='image' are not found in elements array! handle it here
		var $input = $(form.clk), input = $input[0];
		n = input.name;
		if (n && !input.disabled && input.type == 'image') {
			a.push({name: n, value: $input.val()});
			a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
		}
	}
	return a;
};

/**
 * Serializes form data into a 'submittable' string. This method will return a string
 * in the format: name1=value1&amp;name2=value2
 */
$.fn.formSerialize = function(semantic) {
	//hand off to jQuery.param for proper encoding
	return $.param(this.formToArray(semantic));
};

/**
 * Serializes all field elements in the jQuery object into a query string.
 * This method will return a string in the format: name1=value1&amp;name2=value2
 */
$.fn.fieldSerialize = function(successful) {
	var a = [];
	this.each(function() {
		var n = this.name;
		if (!n) {
			return;
		}
		var v = $.fieldValue(this, successful);
		if (v && v.constructor == Array) {
			for (var i=0,max=v.length; i < max; i++) {
				a.push({name: n, value: v[i]});
			}
		}
		else if (v !== null && typeof v != 'undefined') {
			a.push({name: this.name, value: v});
		}
	});
	//hand off to jQuery.param for proper encoding
	return $.param(a);
};

/**
 * Returns the value(s) of the element in the matched set.  For example, consider the following form:
 *
 *  <form><fieldset>
 *	  <input name="A" type="text" />
 *	  <input name="A" type="text" />
 *	  <input name="B" type="checkbox" value="B1" />
 *	  <input name="B" type="checkbox" value="B2"/>
 *	  <input name="C" type="radio" value="C1" />
 *	  <input name="C" type="radio" value="C2" />
 *  </fieldset></form>
 *
 *  var v = $(':text').fieldValue();
 *  // if no values are entered into the text inputs
 *  v == ['','']
 *  // if values entered into the text inputs are 'foo' and 'bar'
 *  v == ['foo','bar']
 *
 *  var v = $(':checkbox').fieldValue();
 *  // if neither checkbox is checked
 *  v === undefined
 *  // if both checkboxes are checked
 *  v == ['B1', 'B2']
 *
 *  var v = $(':radio').fieldValue();
 *  // if neither radio is checked
 *  v === undefined
 *  // if first radio is checked
 *  v == ['C1']
 *
 * The successful argument controls whether or not the field element must be 'successful'
 * (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls).
 * The default value of the successful argument is true.  If this value is false the value(s)
 * for each element is returned.
 *
 * Note: This method *always* returns an array.  If no valid value can be determined the
 *	   array will be empty, otherwise it will contain one or more values.
 */
$.fn.fieldValue = function(successful) {
	for (var val=[], i=0, max=this.length; i < max; i++) {
		var el = this[i];
		var v = $.fieldValue(el, successful);
		if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length)) {
			continue;
		}
		v.constructor == Array ? $.merge(val, v) : val.push(v);
	}
	return val;
};

/**
 * Returns the value of the field element.
 */
$.fieldValue = function(el, successful) {
	var n = el.name, t = el.type, tag = el.tagName.toLowerCase();
	if (successful === undefined) {
		successful = true;
	}

	if (successful && (!n || el.disabled || t == 'reset' || t == 'button' ||
		(t == 'checkbox' || t == 'radio') && !el.checked ||
		(t == 'submit' || t == 'image') && el.form && el.form.clk != el ||
		tag == 'select' && el.selectedIndex == -1)) {
			return null;
	}

	if (tag == 'select') {
		var index = el.selectedIndex;
		if (index < 0) {
			return null;
		}
		var a = [], ops = el.options;
		var one = (t == 'select-one');
		var max = (one ? index+1 : ops.length);
		for(var i=(one ? index : 0); i < max; i++) {
			var op = ops[i];
			if (op.selected) {
				var v = op.value;
				if (!v) { // extra pain for IE...
					v = (op.attributes && op.attributes['value'] && !(op.attributes['value'].specified)) ? op.text : op.value;
				}
				if (one) {
					return v;
				}
				a.push(v);
			}
		}
		return a;
	}
	return $(el).val();
};

/**
 * Clears the form data.  Takes the following actions on the form's input fields:
 *  - input text fields will have their 'value' property set to the empty string
 *  - select elements will have their 'selectedIndex' property set to -1
 *  - checkbox and radio inputs will have their 'checked' property set to false
 *  - inputs of type submit, button, reset, and hidden will *not* be effected
 *  - button elements will *not* be effected
 */
$.fn.clearForm = function() {
	return this.each(function() {
		$('input,select,textarea', this).clearFields();
	});
};

/**
 * Clears the selected form elements.
 */
$.fn.clearFields = $.fn.clearInputs = function() {
	return this.each(function() {

		var t = this.type, tag = this.tagName.toLowerCase();
		if (t == 'text' || t == 'password' || tag == 'textarea') {
			this.value = '';
		}
		else if (t == 'checkbox' || t == 'radio') {
			this.checked = false;
		}
		else if (tag == 'select') {
			this.selectedIndex = -1;
		}
	});
};

/**
 * Resets the form data.  Causes all form elements to be reset to their original value.
 */
$.fn.resetForm = function() {
	return this.each(function() {
		// guard against an input with the name of 'reset'
		// note that IE reports the reset function as an 'object'
		if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType)) {
			this.reset();
		}
	});
};

/**
 * Enables or disables any matching elements.
 */
$.fn.enable = function(b) {
	if (b === undefined) {
		b = true;
	}
	return this.each(function() {
		this.disabled = !b;
	});
};

/**
 * Checks/unchecks any matching checkboxes or radio buttons and
 * selects/deselects and matching option elements.
 */
$.fn.selected = function(select) {
	if (select === undefined) {
		select = true;
	}
	return this.each(function() {
		var t = this.type;
		if (t == 'checkbox' || t == 'radio') {
			this.checked = select;
		}
		else if (this.tagName.toLowerCase() == 'option') {
			var $sel = $(this).parent('select');
			if (select && $sel[0] && $sel[0].type == 'select-one') {
				// deselect all other options
				$sel.find('option').selected(false);
			}
			this.selected = select;
		}
	});
};

// helper fn for console logging
function log() {
	var msg = '[jquery.form] ' + Array.prototype.join.call(arguments,'');
	if (window.console && window.console.log) {
		window.console.log(msg);
	}
	else if (window.opera && window.opera.postError) {
		window.opera.postError(msg);
	}
};

})(jQuery);



 // File: _mw.js 


/*var mw_edit = document.createElement("edit");
 var mw_module = document.createElement("module");
 var mw_moduleedit = document.createElement("moduleedit");
 var mw_editblock = document.createElement("editblock");*/

if (window.console != undefined) {
	console.log('Microweber Javascript Framework Loaded');
}

/*
 * Microweber - Javascript Framework
 * 
 * Copyright (c) Mass Media Group (www.ooyes.net) Licensed under the Microweber
 * license http://microweber.com/license
 * 
 */

window.mw = window.mw ? window.mw : {};
MW = window.mw;
mw = window.mw;

mw.ready = function(elem, callback) {

	$(document).ready(function() {
		$(elem).each(function() {
			var el = $(this);
			if (!el.hasClass("exec")) {
				el.addClass("exec");
				callback.call(el);
			}
		});

		$(document.body).ajaxStop(function() {
			$(elem).each(function() {
				var el = $(this);
				if (!el.hasClass("exec")) {
					el.addClass("exec");
					callback.call(el);
				}
			});
		});

	});

}

mw.module = function($vars, $update_element) {

	$.ajax( {
		url : 'http://newsletter.leadersrules.com/api/module',
		type : "POST",
		data : ($vars),
		async : false,

		success : function(resp) {
			$($update_element).html(resp);

			if ($vars.callback != undefined) {
				$vars.callback.call(this);

			}

		}
	});
}

mw.reload_module = function($module_name) {
	
	
	if ($module_name == undefined) {

	} else {
		var module_name = $module_name.toString();
		refresh_modules_explode = module_name.split(",");
	//	alert(refresh_modules_explode);
		for ( var i = 0; i < refresh_modules_explode.length; i++) {
			var $module_name = refresh_modules_explode[i];

			
			
			
			if ($module_name != undefined) { 
			//	$("div.module").each(
				//$("div.module[mw_params_module='"+$module_name+"']").each(
				$("div.module").each(
 								function() {

									var mw_params_module = $(this).attr(	"mw_params_module");
									var mw_params_module_id = $(this).attr(	"module_id");
									
									mw_params_module = mw_params_module.replace(/\\/g,"/"); 
									
								//$all_attr = 	 $.getAttributes('#foo'), true );
									$all_attr =  $(this).getAttributes();
									
									if (mw_params_module != $module_name) {
										// var mw_params_module =
										// $(this).attr("id");
										// alert(mw_params_module);
									}

						 
									if (window.console != undefined) {
							 		//	console.log('Reload module   ' + mw_params_module  +mw_params_module_id + '  ' + $module_name);	
							 		}
									
									if (mw_params_module == $module_name || mw_params_module_id == $module_name) {
										var mw_params_encoded = $(this).attr(	"mw_params_encoded");
										var elem = $(this)
										
		
								 
										 url1= 'http://newsletter.leadersrules.com/api/module/index/reload_module:' + mw_params_encoded;
										 elem.load(url1,$all_attr,function() {
											 window.mw_sortables_created = false;
										 }); 
										 
										 
										 
										
										 
											

//										$.ajax( {
//													url : 'http://newsletter.leadersrules.com/api/module/index/reload_module:' + mw_params_encoded,
//													type : "POST",
//													data: $all_attr,
//													async : false,
//
//													success : function(resp) {
//												//	alert(resp);
//														//$(this).empty();
//											elem.before(resp).remove(); 
//													// elem.empty();
//													// elem.append(resp);
//
//												}
//												});

									}

								});

			}

		}
		 if(typeof init_edits == 'function') { 
		//	 window.mw_sortables_created = false;
			// init_edits(); 
			 }
		 
	//	 $('.mw').trigger('mw_module_reloaded', [$module_name]);

	}

}

mw.clear_cache = function() {
	$.ajax( {
		url : 'http://newsletter.leadersrules.com/ajax_helpers/clearcache',
		type : "POST",
		success : function(resp) {

		}
	});
}






 // File: utils.js 

mw.utils = {};
mw.utils.elementBlink =  function(elementId, duration) {
	if (!duration) {
		duration = 400;
	}
	$('#' + elementId).fadeOut(duration, function() {
		$('#' + elementId).fadeIn(duration);
	});
}

mw.browser = {
	msie : function() {
		return (document.all && window.external) ? true : false;
	},
	msie6 : function() {
		return (!window.XMLHttpRequest) ? true : false;
	},
	msie7 : function() {
		return (document.all && (!window.XDomainRequest) && window.XMLHttpRequest) ? true
				: false;
	},
	msie8 : function() {
		return window.XDomainRequest ? true : false;
	},
	opera : function() {
		return window.opera ? true : false;
	},
	firefox : function() {
		return (window.globalStorage && window.postMessage) ? true : false;
	},
	chrome : function() {
		return window.chrome ? true : false;
	},
	safari : function() {
		return ((document.childNodes) && (!document.all)
				&& (!navigator.taintEnabled) && (!navigator.accentColorName) && (!window.chrome)) ? true
				: false;
	},
	webkit : function() {
		return (typeof document.body.style.webkitBorderRadius != "undefined") ? true
				: false;
	},
	khtml : function() {
		return (navigator.vendor == "KDE") ? true : false;
	},
	konqueror : function() {
		return ((navigator.vendor == 'KDE') || (document.childNodes)
				&& (!document.all) && (!navigator.taintEnabled)) ? true : false;
	}

}

var Base64 = {

	// private property
	_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

	// public method for encoding
	encode : function(input) {
		var output = "";
		var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
		var i = 0;

		input = Base64._utf8_encode(input);

		while (i < input.length) {

			chr1 = input.charCodeAt(i++);
			chr2 = input.charCodeAt(i++);
			chr3 = input.charCodeAt(i++);

			enc1 = chr1 >> 2;
			enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
			enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
			enc4 = chr3 & 63;

			if (isNaN(chr2)) {
				enc3 = enc4 = 64;
			} else if (isNaN(chr3)) {
				enc4 = 64;
			}

			output = output + this._keyStr.charAt(enc1)
					+ this._keyStr.charAt(enc2) + this._keyStr.charAt(enc3)
					+ this._keyStr.charAt(enc4);

		}

		return output;
	},

	// public method for decoding
	decode : function(input) {
		var output = "";
		var chr1, chr2, chr3;
		var enc1, enc2, enc3, enc4;
		var i = 0;

		input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

		while (i < input.length) {

			enc1 = this._keyStr.indexOf(input.charAt(i++));
			enc2 = this._keyStr.indexOf(input.charAt(i++));
			enc3 = this._keyStr.indexOf(input.charAt(i++));
			enc4 = this._keyStr.indexOf(input.charAt(i++));

			chr1 = (enc1 << 2) | (enc2 >> 4);
			chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
			chr3 = ((enc3 & 3) << 6) | enc4;

			output = output + String.fromCharCode(chr1);

			if (enc3 != 64) {
				output = output + String.fromCharCode(chr2);
			}
			if (enc4 != 64) {
				output = output + String.fromCharCode(chr3);
			}

		}

		output = Base64._utf8_decode(output);

		return output;

	},

	// 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;
	}

}

function serialize (mixed_value) {
    // http://kevin.vanzonneveld.net
    // +   original by: Arpad Ray (mailto:arpad@php.net)
    // +   improved by: Dino
    // +   bugfixed by: Andrej Pavlovic
    // +   bugfixed by: Garagoth
    // +      input by: DtTvB (http://dt.in.th/2008-09-16.string-length-in-bytes.html)
    // +   bugfixed by: Russell Walker (http://www.nbill.co.uk/)
    // +   bugfixed by: Jamie Beck (http://www.terabit.ca/)
    // +      input by: Martin (http://www.erlenwiese.de/)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net/)
    // +   improved by: Le Torbi (http://www.letorbi.de/)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net/)
    // +   bugfixed by: Ben (http://benblume.co.uk/)
    // -    depends on: utf8_encode
    // %          note: We feel the main purpose of this function should be to ease the transport of data between php & js
    // %          note: Aiming for PHP-compatibility, we have to translate objects to arrays
    // *     example 1: serialize(['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: 'a:3:{i:0;s:5:"Kevin";i:1;s:3:"van";i:2;s:9:"Zonneveld";}'
    // *     example 2: serialize({firstName: 'Kevin', midName: 'van', surName: 'Zonneveld'});
    // *     returns 2: 'a:3:{s:9:"firstName";s:5:"Kevin";s:7:"midName";s:3:"van";s:7:"surName";s:9:"Zonneveld";}'

	var _utf8Size = function (str) {
	    var size = 0, i = 0, l = str.length, code = '';
	    for (i = 0; i < l; i++) {
	        code = str.charCodeAt(i);
	        if (code < 0x0080) {
	            size += 1;
	        } else if (code < 0x0800) {
	            size += 2;
	        } else {
	        	size += 3;
			}
	    }
	    return size;
	};
    var _getType = function (inp) {
        var type = typeof inp, match;
        var key;

        if (type === 'object' && !inp) {
            return 'null';
        }
        if (type === "object") {
            if (!inp.constructor) {
                return 'object';
            }
            var cons = inp.constructor.toString();
            match = cons.match(/(\w+)\(/);
            if (match) {
                cons = match[1].toLowerCase();
            }
            var types = ["boolean", "number", "string", "array"];
            for (key in types) {
                if (cons == types[key]) {
                    type = types[key];
                    break;
                }
            }
        }
        return type;
    };
    var type = _getType(mixed_value);
    var val, ktype = '';
    
    switch (type) {
        case "function": 
            val = ""; 
            break;
        case "boolean":
            val = "b:" + (mixed_value ? "1" : "0");
            break;
        case "number":
            val = (Math.round(mixed_value) == mixed_value ? "i" : "d") + ":" + mixed_value;
            break;
        case "string":
			val = "s:" + _utf8Size(mixed_value) + ":\"" + mixed_value + "\"";
            break;
        case "array":
        case "object":
            val = "a";
            /*
            if (type == "object") {
                var objname = mixed_value.constructor.toString().match(/(\w+)\(\)/);
                if (objname == undefined) {
                    return;
                }
                objname[1] = this.serialize(objname[1]);
                val = "O" + objname[1].substring(1, objname[1].length - 1);
            }
            */
            var count = 0;
            var vals = "";
            var okey;
            var key;
            for (key in mixed_value) {
			    if (mixed_value.hasOwnProperty(key)) {
               	   ktype = _getType(mixed_value[key]);
	               if (ktype === "function") { 
	                   continue; 
	               }
               
	               okey = (key.match(/^[0-9]+$/) ? parseInt(key, 10) : key);
	               vals += this.serialize(okey) +
	                       this.serialize(mixed_value[key]);
	               count++;
		        }
            }
            val += ":" + count + ":{" + vals + "}";
            break;
        case "undefined": // Fall-through
        default: // if the JS object has a property which contains a null value, the string cannot be unserialized by PHP
            val = "N";
            break;
    }
    if (type !== "object" && type !== "array") {
        val += ";";
    }
    return val;
}

function base64Encode(text){

    if (/([^\u0000-\u00ff])/.test(text)){
        throw new Error("Can't base64 encode non-ASCII characters.");
    } 

    var digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
        i = 0,
        cur, prev, byteNum,
        result=[];      

    while(i < text.length){

        cur = text.charCodeAt(i);
        byteNum = i % 3;

        switch(byteNum){
            case 0: //first byte
                result.push(digits.charAt(cur >> 2));
                break;

            case 1: //second byte
                result.push(digits.charAt((prev & 3) << 4 | (cur >> 4)));
                break;

            case 2: //third byte
                result.push(digits.charAt((prev & 0x0f) << 2 | (cur >> 6)));
                result.push(digits.charAt(cur & 0x3f));
                break;
        }

        prev = cur;
        i++;
    }

    if (byteNum == 0){
        result.push(digits.charAt((prev & 3) << 4));
        result.push("==");
    } else if (byteNum == 1){
        result.push(digits.charAt((prev & 0x0f) << 2));
        result.push("=");
    }

    return result.join("");
}

mw.prevent = function(event){

    if (event.stopPropagation) {
        event.stopPropagation();
    } else {
        event.cancelBubble = true;
    }
    event.preventDefault();
}

mw.image = {}
mw.image.edit = {
  over:function(image){
    var left = $(image).offset().left;
    var top = $(image).offset().top;
    var edit = document.createElement('a');
        edit.innerHTML = 'Edit';
        edit.className = 'mw_image_edit mw_image';
        edit.style.left = left + 10 + 'px';
        edit.style.top = top + 10 + 'px';
        edit.style.position = 'absolute';
        edit.style.zIndex = '10';
    var del = document.createElement('a');
        del.innerHTML = 'Delete';
        del.className = 'mw_image_del mw_image';
        del.style.left = left + 60 + 'px';
        del.style.top = top + 10 + 'px';
        del.style.position = 'absolute';
        del.style.zIndex = '10';
    var url = $(image).attr("src");
    $(edit).click(function(){
       mw.image.edit.popup(url);
    });
    $(edit).hover(function(){
        $(this).addClass("mw_image_edit_hover")
    }, function(){
        $(this).removeClass("mw_image_edit_hover")
    });

    $(del).click(function(){
       mw.image.edit.del(image);
    });
    $(del).hover(function(){
        $(this).addClass("mw_image_edit_hover")
    }, function(){
        $(this).removeClass("mw_image_edit_hover")
    });

    document.body.appendChild(edit);
    document.body.appendChild(del);

  },
  del:function(image){
    mw.modal.confirm({
      yes:function(){
        $(image).remove()
        $(".mw_image").remove();
      },
      html:"Are you sure you want to delete this image?"
    })

  },
  out:function(image){
    setTimeout(function(){
      if($(".mw_image_edit_hover").length==0){
         $(".mw_image").remove();
      }
    }, 10)
  },
  popup:function(url){
    mw.modal.init({
      width: 700,
      height: 600,
      id:'mw_image_edit_pop',
      oninit:function(){
         $(".mw_image").remove();
      },
      html:"<img src='" + url + "' />"
    })
  },
  init:function(image){


     $(image).hover(function(){
        $(this).addClass("mw_image_edit_hover");
        if($(".mw_image").length==0){
          mw.image.edit.over(image);
        }
     }, function(){
        $(this).removeClass("mw_image_edit_hover");
        mw.image.edit.out(image)
     });
  },
  disable:function(image){
    $(image).unbind('mouseenter mouseleave');
  }
}

mw.outline ={
  init:function(elem, color, $size){
    $(elem).each(function(){
      var width = $(this).outerWidth();
	  
	  if($size != undefined){
		//   var width = $size+'px'; 
	  } else {
		$size = 2;  
	  }
	  
      var height = $(this).outerHeight();
      var left = $(this).offset().left;
      var top = $(this).offset().top;

      var line_top = document.createElement('div');
      var line_right = document.createElement('div');
      var line_bottom = document.createElement('div');
      var line_left = document.createElement('div');
      var cls = elem.replace("#", "");
      var cls = cls.replace(".", "");
      $(line_top).addClass("mw_outline mw_outline_" + cls);
      $(line_right).addClass("mw_outline mw_outline_" + cls);
      $(line_bottom).addClass("mw_outline mw_outline_" + cls);
      $(line_left).addClass("mw_outline mw_outline_" + cls);

      $(line_top).addClass("mw_outline_top").css({
        top:top,
        left:left,
        width:width,
        backgroundColor:color==undefined?"#0000CC":color
      });
      $(line_right).addClass("mw_outline_right").css({
        top:top,
        left:left+width-$size,
        height:height,
        backgroundColor:color==undefined?"#0000CC":color
      });
      $(line_bottom).addClass("mw_outline_bottom").css({
        top:top+height-$size,
        left:left,
        width:width,
        backgroundColor:color==undefined?"#0000CC":color
      });
      $(line_left).addClass("mw_outline_left").css({
        top:top,
        left:left,
        height:height,
        backgroundColor:color==undefined?"#0000CC":color
      });

      document.body.appendChild(line_top)
      document.body.appendChild(line_right)
      document.body.appendChild(line_bottom)
      document.body.appendChild(line_left)


    });
  },
  
  
  
  
   removeAll:function(){
	   
	     $(".mw_outline").remove();
	  },
  
  
  remove:function(elem){
    var cls = elem.replace("#", "");
      var cls = cls.replace(".", "");
     $(".mw_outline_" + cls).remove();
  }
}
mw.buildURL = function(string, elem){


    				var string = string.toLowerCase() // change everything to lowercase
    				.replace(/^\s+|\s+$/g, "") // trim leading and trailing spaces
    				.replace(/[_|\s]+/g, "-") // change all spaces and underscores to a hyphen
    				.replace(/[^a-z\u0400-\u04FF0-9-]+/g, "") // remove all non-cyrillic, non-numeric characters except the hyphen
    				.replace(/[-]+/g, "-") // replace multiple instances of the hyphen with a single instance
    				.replace(/^-+|-+$/g, "") // trim leading and trailing hyphens
    				.replace(/[-]+/g, "-");


    				var string = CLconvert(string);


    if(elem!=undefined && $(elem).val()==""){
      $(elem).val(string);
    }
    return string;
}





	var cyrillic = [
		"а", "б", "в", "г", "д", "е", "ж", "з", "и", "й", "к", "л", "м", "н", "о",
		"п", "р", "с", "т", "у", "ф", "х", "ц", "ч", "ш", "щ", "ъ", "ь", "ю", "я",
		"А", "Б", "В", "Г", "Д", "Е", "Ж", "З", "И", "Й", "К", "Л", "М", "Н", "О",
		"П", "Р", "С", "Т", "У", "Ф", "Х", "Ц", "Ч", "Ш", "Щ", "Ъ", "Ь", "Ю", "Я",
		"Ї", "ї", "Є", "є", "Ы", "ы", "Ё", "ё"
	];

	var latin = [
		"a", "b", "v", "g", "d", "e", "zh", "z", "i", "y", "k", "l", "m", "n", "o",
		"p", "r", "s", "t", "u", "f", "h", "ts", "ch", "sh", "sht", "a", "y", "yu", "ya",
		"A", "B", "B", "G", "D", "E", "Zh", "Z", "I", "Y", "K", "L", "M", "N", "O",
		"P", "R", "S", "T", "U", "F", "H", "Ts", "Ch", "Sh", "Sht", "A", "Y", "Yu", "Ya",
		"I", "i", "Ye", "ye", "I", "i", "Yo", "yo"
	];



		function CLconvert (text) {
			string = str_replace(cyrillic, latin, text);
			return string;
		}

		function str_replace (search, replace, subject, count) {

		    var i = 0, j = 0, temp = '', repl = '', sl = 0, fl = 0,
		            f = [].concat(search),
		            r = [].concat(replace),
		            s = subject,
		            ra = r instanceof Array, sa = s instanceof Array;
		    s = [].concat(s);
		    if (count) {
		        this.window[count] = 0;
		    }

		    for (i=0, sl=s.length; i < sl; i++) {
		        if (s[i] === '') {
		            continue;
		        }
		        for (j=0, fl=f.length; j < fl; j++) {
		            temp = s[i]+'';
		            repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
		            s[i] = (temp).split(f[j]).join(repl);
		            if (count && s[i] !== temp) {
		                this.window[count] += (temp.length-s[i].length)/f[j].length;}
		        }
		    }

		    return sa ? s : s[0];
		}






mw.isJSGenerated = function(elem, callback){
    $(elem).each(function(){
      if(!$(this).hasClass("js_generated")){
         var elem = this;
         callback.call(elem);
         $(this).addClass("js_generated")
      }
    });
}



mw.singleline = function(string){
    return string.replace("\n", "");
}

mw.randColor = function(){
   return 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';
}














































 // File: content.js 

mw.content = {};
mw.content.CategoriesTree = function() {

	this.servicesUrl = 'http://newsletter.leadersrules.com/ajax_helpers/';

	this.loadArticles = function(authorId, categoryId) {
		$.post(this.servicesUrl + 'categoty_get_articles_list', {
			categoryId : categoryId,
			authorId : authorId
		}, function(response) {
			// $('#sidebar_recent_posts_list').html(response);
				return response;
			});
	};

}

mw.content.del = function(post_id, hide_element_or_callback) {
	var answer = confirm("Are you sure you want to delete this?");

	if (answer) {

		$.post('http://newsletter.leadersrules.com/api/content/delete', {
			id : post_id
		}, function(response) {
			if (response.indexOf('yes')!=-1) {
				if (typeof (hide_element_or_callback) == 'function') {
					hide_element_or_callback.call(this);
				} else {
					$(hide_element_or_callback).fadeOut();
				}
			} else {
				alert(response);
			}
		});

	}

}

mw.content.save = function($form_selector, $callback) {
	$data = ($($form_selector).serialize());

	$.ajax( {
		type : "POST",
		url : "http://newsletter.leadersrules.com/api/content/save_post",
		data : $data,
		dataType: 'json',
		success : function(msg) {
			//alert("Data: " + msg);
		 // $('.cart_items_qty').html(msg);
 
		if (typeof  $callback == 'function') {
			$callback.call(this, msg);
		} else {
			$($callback).fadeOut();
		}
		
		
		
		
			
		}
	});

}


mw.content.Vote = function(toTable, toTableId, updateElementSelector) {

	$.post('http://newsletter.leadersrules.com/api/content/vote', {
		t : toTable,
		tt : toTableId
	}, function(response) {

		if (response.indexOf("yes")!= -1) {
			$(updateElementSelector).each(function() {
				$(this).html(parseFloat($(this).html()) + 1);
			});

			eventlistener = 'onAfterVote';

			return;
		}

		if ((response.valueOf()) == 'no') {
			// mw.box.notification('You have already voted!')
			// return 'You have already voted!';
			// alert('asd');
			// mw.box.alert('You have already liked this!');
		}

		if (response == 'login required') {
			if ((response.valueOf()) == 'login required') {
				mw.users.AjaxLogin();
			} else {
				mw.box.notification(response)
			}
		}

	});
}

mw.content.report = function(toTable, toTableId, updateElementSelector) {
	$.post('http://newsletter.leadersrules.com/api/content/report', {
		t : toTable,
		tt : toTableId
	}, function(response) {
		if (response.indexOf("yes")== true) {

			$(updateElementSelector).each(function() {
				var curr = parseFloat($(this).html());
				if (!isNaN(curr)) {
					$(this).html(curr + 1);
				}

			});

		}

		if (response == 'login required') {

			if ((response.valueOf()) == 'login required') {

				mw.users.AjaxLogin();

			} else {

				mw.box.notification(response)
			}
		}

	});
}


 // File: user.js 

mw.users = {};

mw.users.get = function() {
	alert('get');

};

mw.users.AjaxLogin = function($redirect_to) {
	if ($redirect_to == false) {
		$back_location = (window.location.href);
	} else {
		$back_location = ($redirect_to);
	}

	$backto = Base64.encode($back_location)
	mw.box.remove();
	mw.box.overlay();
	mw.box.ajax( {
		url : 'http://newsletter.leadersrules.com/users/user_action:login_ajax/back_to:' + $backto,
		width : 350,
		height : 280,
		id : 'ajax_login'
	});
	msRoundedField();
}


mw.users.register = function($form_selector, $callback) {
	$data = ($($form_selector).serialize());

	$.ajax( {
		type : "POST",
		url : "http://newsletter.leadersrules.com/api/user/register",
		data : $data,
		dataType: 'json',
		success : function(msg) {
			//alert("Data: " + msg);
		 // $('.cart_items_qty').html(msg);
 
		if (typeof  $callback == 'function') {
			$callback.call(this, msg);
		} else {
			$($callback).fadeOut();
		}
		
		
		
		
			
		}
	});

}

mw.users.login = function($form_selector, $callback) {
	$data = ($($form_selector).serialize());

	$.ajax( {
		type : "POST",
		url : "http://newsletter.leadersrules.com/api/user/login",
		data : $data,
		dataType: 'json',
		success : function(msg) {
			//alert("Data: " + msg);
		 // $('.cart_items_qty').html(msg);
 
		if (typeof  $callback == 'function') {
			$callback.call(this, msg);
		} else {
			//$($callback).fadeOut();
		}
		
		
		
		
			
		}
	});

}


mw.users.save = function($form_selector, $callback) {
	$data = ($($form_selector).serialize());

	$.ajax( {
		type : "POST",
		url : "http://newsletter.leadersrules.com/api/user/save",
		data : $data,
		dataType: 'json',
		success : function(msg) {
			//alert("Data: " + msg);
		 // $('.cart_items_qty').html(msg);
 
		if (typeof  $callback == 'function') {
			$callback.call(this, msg);
		} else {
			$($callback).fadeOut();
		}
		
		
		
		
			
		}
	});

}


mw.users.ChangePass = function() {
	// $back_location = (window.location.href);
	// $backto = Base64.encode($back_location)
	mw.box.remove();
	mw.box.overlay();
	$.post('http://newsletter.leadersrules.com/users/user_action:password/', function(data) {
		var checker = document.createElement('div');
		checker.innerHTML = data;
		if ($(checker).find("meta").length == 0) {
			mw.box.html( {
				width : 370,
				height : 340,
				html : data,
				id : 'change_password_modal_window'
			});
		} else {
			window.location.href = 'http://newsletter.leadersrules.com/users/user_action:login/';
		}

	});

}

mw.users.LogOut = function() {

	$.ajax( {
		async : false,
		url : "http://newsletter.leadersrules.com/fb_login/logout",
		context : document.body,
		success : function() {

		}
	});

	$.ajax( {
		async : false,
		url : "http://newsletter.leadersrules.com/api/user/logOut",
		context : document.body,
		success : function() {
			window.location.reload();
		}
	});

}

mw.users.UserMessage = new function() {

	this.servicesUrl = 'http://newsletter.leadersrules.com/ajax_helpers/message_';

	/* ~~~ private methods ~~~ */

	this._beforeSend = function() {

		var isValid;
		if ($("#message_form").hasClass("error")) {
			isValid = false;
		} else {
			isValid = true;
		}

		return isValid;
	};

	this._afterSend = function() {
		window.location.reload();
	};

	/* ~~~ public methods ~~~ */

	this.send = function() {

		var requestOptions = {
			// url : this.servicesUrl + 'send',
			url : 'http://newsletter.leadersrules.com/api/user/message_send',
			clearForm : true,
			type : 'post',
			beforeSubmit : this._beforeSend,
			success : function(response) {
				mw.box.remove();
				// mwbox.notification(response)
			window.location.reload();
		}
		};

		$('#message_form').ajaxSubmit(requestOptions);
		return false;
	};

	this.sendQuick = function($form) {
		$form = $($form).parents("form");
		var $form = $($form);
		var requestOptions = {
			url : 'http://newsletter.leadersrules.com/api/user/message_send',
			clearForm : true,
			type : 'post',
			beforeSubmit : this._beforeSend,
			success : function(response) {

				mw.box.remove();
				mw.box.alert("<h2 style='text-align:center'>" + response
						+ "</h2>")
			}
		};

		$form.ajaxSubmit(requestOptions);
		return false;
	};

	this.read = function(id) {
		$.post('http://newsletter.leadersrules.com/api/user/message_read', {
			id : id
		}, function(response) {
			if (parseInt(response) == parseInt(id)) {
				// $('#messageReadControl-'+id).attr({
				// title: 'Mark as unread',
				// onclick: 'UserMessage.unread('+id+');'
				// });
				// $('#messageReadControl-'+id).click(function(){
				// UserMessage.unread(id);
				// });
				// mw.utils.elementBlink('messageReadControl-'+id);
				$('#messageItem-' + id).removeClass('messageUnread').addClass(
						'messageRead');
			}
		});
	};

	this.unread = function(id) {
		$.post('http://newsletter.leadersrules.com/api/user/message_unread', {
			id : id
		}, function(response) {
			if (parseInt(response) == parseInt(id)) {
				// $('#messageReadControl-'+id).attr({
				// title: 'Mark as read',
				// onclick: 'UserMessage.read('+id+');'
				// });
				// $('#messageReadControl-'+id).click(function(){
				// UserMessage.read(id);
				// });
				// show that something happens
				// mw.utils.elementBlink('messageReadControl-'+id);
				$('#messageItem-' + id).removeClass('messageRead').addClass(
						'messageUnread');

			}
		});
	};

	this.del = function(id, itemContainerId) {

		$.post(

		'http://newsletter.leadersrules.com/api/user/message_delete', {
			id : id
		}, function(response) {
			if (parseInt(response) == parseInt(id)) {
				$('#' + itemContainerId).fadeOut(300, function() {
					$('#' + itemContainerId).remove();
				});
			}
		});
	};

	this._getSelected = function() {

		// sdfsd-123
		var ids = [];
		var counter = 0;

		$("input[id*='messageReadControl-']").each(
				function() {
					if ($(this).is(":checked")) {
						ids[counter] = $(this).attr("id").replace(
								'messageReadControl-', '');
						counter++;
					}
				});

		return ids;
	};

	this.readSelected = function() {
		var ids = this._getSelected();
		for ( var i = 0; i < ids.length; i++) {
			this.read(ids[i]);
		}

	};

	this.unreadSelected = function() {
		var ids = this._getSelected();
		for ( var i = 0; i < ids.length; i++) {
			this.unread(ids[i]);
		}
	};

	this.deleteSelected = function() {
		var ids = this._getSelected();
		for ( var i = 0; i < ids.length; i++) {
			this.del(ids[i], 'messageItem-' + ids[i]);
		}
	};

	this.selectAll = function() {

		$("input[id*='messageReadControl-']").check();
	};

	this.deselectAll = function() {

		$("input[id*='messageReadControl-']").uncheck();
	};

	this.compose = function(to, conversation) {

		var params = '';
		if (to) {
			params += '/to:' + to;
		}
		if (conversation) {
			params += '/conversation:' + conversation;
		}
		// mwbox.displayAjax(this.servicesUrl + 'send_form' + params, 400, 300);
		mw.box.remove();
		/*
		 * mw.box.ajax( { url : 'http://newsletter.leadersrules.com/dashboard/action:message_compose/' +
		 * params, width : 400, height : 360, id : 'messagecompose' });
		 */

		var params = {
			module : "messages/compose",
			to : to,
			conversation : conversation
		}

		$.post("http://newsletter.leadersrules.com/api/module", params, function(data) {

			mw.box.html( {
				html : data,
				width : 430,
				height : 360,
				id : 'messagecompose'
			})
		})

	};

}

mw.users.log_delete = function(post_id, hide_element_or_callback) {
	var answer = confirm("Are you sure you want to delete this?");

	if (answer) {

		$.post('http://newsletter.leadersrules.com/api/user/delete_log_item', {
			id : post_id
		}, function(response) {

			// if (response == 'yes') {
				if (typeof (hide_element_or_callback) == 'function') {
					hide_element_or_callback.call(this);
				} else {
					$(hide_element_or_callback).fadeOut();
				}
				// } else {
				// alert(response);
				// }

			});

	}

}

// Message class
mw.users.UserNotification = new function() {

	this.servicesUrl = 'http://newsletter.leadersrules.com/ajax_helpers/';

	/* ~~~ private methods ~~~ */

	this.read = function(id) {

		if ($('#notificationItem-' + id).hasClass('messageUnread')) {
			$('#notificationItem-' + id).removeClass('messageUnread');
			$.post('http://newsletter.leadersrules.com/api/user/notification_read', {
				id : id
			}, function(response) {
				if (parseInt(response) == parseInt(id)) {

					$('#notificationItem-' + id).addClass('messageRead');
					// $('#notificationItem-' + id).fadeIn(400);

				}
			});
		}
	};

	this.remove = function(id) {
		$.post('http://newsletter.leadersrules.com/api/user/notification_delete', {
			id : id
		}, function(response) {
			if (parseInt(response) == parseInt(id)) {
				$('#notificationItem-' + id).fadeOut(300, function() {
					$('#notificationItem-' + id).remove();
				});
			}
		});

	};

}

// Follow class
mw.users.FollowingSystem = new function() {

	// this.servicesUrl = 'http://newsletter.leadersrules.com/ajax_helpers/',
			this.servicesUrl = 'http://newsletter.leadersrules.com/api/user/followingSystem',
			/* ~~~ private methods ~~~ */

			this._follow = function(follower_id, follow, special, cancel) {
				$.post(this.servicesUrl, {
					follower_id : follower_id,
					follow : follow,
					cancel : cancel,
					special : special
				}, function(response) {
					// alert("Response: " + response);
						if (response.length > 0) {

							if ((response.valueOf()) == 'login required') {

								mw.users.AjaxLogin();

							} else {
								$(".box-ico-follow").hide();
								$(".box-ico-unfollow").hide();
								mw.box.notification( {
									html : response
								});
							}

						}
					});
			};

	/* ~~~ public methods ~~~ */

	this.follow = function(follower_id, special, hide_element_or_callback) {
		this._follow(follower_id, 1, special);

		if (typeof (hide_element_or_callback) == 'function') {
			hide_element_or_callback.call(this);
		} else {
			$(hide_element_or_callback).fadeOut();
		}

	};

	this.unfollow = function(follower_id, itemContainerId) {
		// this._follow(follower_id, 0);
		this._follow(follower_id, 0, 0, 1);
		/*
		 * $('#' + itemContainerId).fadeOut(300, function() { $('#' +
		 * itemContainerId).remove(); });
		 */
		$(itemContainerId).fadeOut();

	};
	this.cancel_relationship = function(follower_id, itemContainerId) {
		this._follow(follower_id, 0, 0, 1);
		/*
		 * $('#' + itemContainerId).fadeOut(300, function() { $('#' +
		 * itemContainerId).remove(); });
		 */
		$(itemContainerId).fadeOut();

	};

	this.makeSpecial = function(followers_ids) {
		/*
		 * for ( var i = 0; i < followers_ids.length; i++) {
		 *  }
		 */
		this._follow(followers_ids, 1, 1);
	};

}

// Message class

mw.users.delete_user =  function($id, hide_element_or_callback) {
	var answer = confirm("Are you sure you want to delete this user?");

	if (answer) {

		$.post('http://newsletter.leadersrules.com/api/user/delete_user', {
			id : $id
		}, function(response) {

			// if (response == 'yes') {
				if (typeof (hide_element_or_callback) == 'function') {
					hide_element_or_callback.call(this);
				} else {
					$(hide_element_or_callback).fadeOut();
				}
				// } else {
				// alert(response);
				// }

			});

	}
}

mw.users.User = new function() {

	this.servicesUrl = 'http://newsletter.leadersrules.com/ajax_helpers/',

	/* ~~~ private methods ~~~ */

	this._beforeSend = function() {

		var isValid;
		if ($("#update-status").hasClass("error")) {
			isValid = false;
		} else {
			isValid = true;
		}

		return isValid;
	}

	this._afterSend = function(hide_element_or_callback) {

		setTimeout(function() {

			$("#update-status").fadeOut();
			$("#update-status").fadeIn();
			$("#update-status-done").fadeIn();
			$("#update-status-done").fadeOut(5000);

			if (typeof (hide_element_or_callback) == 'function') {
				hide_element_or_callback.call(this);
			} else {
				$(hide_element_or_callback).fadeOut();
			}

		}, 500);

	}

	/* ~~~ public methods ~~~ */

	this.statusUpdate = function(form, hide_element_or_callback) {
		if (!form) {
			form = $('#update-status');
		} else {
			form = $(form);
		}
		var requestOptions = {
			url : 'http://newsletter.leadersrules.com/api/user/status_update',
			clearForm : false,
			async : false,
			type : 'post',
			beforeSubmit : this._beforeSend,
			success : this._afterSend(hide_element_or_callback)
		};
		form.ajaxSubmit(requestOptions);
		return false;
	};

}

mw.users.Dashboard = new function() {

	this.servicesUrl = 'http://newsletter.leadersrules.com/ajax_helpers/';

	this.getCounts = function(statusesIds, contentsIds) {
		$.post(this.servicesUrl + 'dashboardCounts', {
			statusesIds : statusesIds,
			contentsIds : contentsIds
		}, function(response) {

			// load votes stats
				var stats = response['statuses'];
				for ( var i = 0; i < stats['votes'].length; i++) {
					var itemId = stats['votes'][i]['item_id'];
					var etemValue = stats['votes'][i]['votes_total'];
					$('#status-votes-' + itemId).html(etemValue);
				}
				for ( var i = 0; i < stats['comments'].length; i++) {
					var itemId = stats['comments'][i]['item_id'];
					var etemValue = stats['comments'][i]['comments_total'];
					$('#status-comments-' + itemId).html(etemValue);
				}

				// load comments stats
				stats = response['contents'];
				for ( var i = 0; i < stats['votes'].length; i++) {
					var itemId = stats['votes'][i]['item_id'];
					var etemValue = stats['votes'][i]['votes_total'];
					$('#content-votes-' + itemId).html(etemValue);
				}
				for ( var i = 0; i < stats['comments'].length; i++) {
					var itemId = stats['comments'][i]['item_id'];
					var etemValue = stats['comments'][i]['comments_total'];
					$('#content-comments-' + itemId).html(etemValue);
				}

			}, "json");
	};

	this.comment = function() {
		alert("Add comment");
	};

	this.vote = function() {
		alert("Vote item");
	};

}



 // File: comments.js 

$(document).ready(function(){

});


mw.comments = {};

mw.comments = new function() {

	this.servicesUrl = 'http://newsletter.leadersrules.com//ajax_helpers/',
	
	 this.ajax_element_update = false,
	
 
	

	

	
	
	this._beforeSend = function(formData, jqForm, options) {
		var queryString = $.param(formData);
		var isValid;
		this.ajax_element_update = false;



		if ($(".ajax_comment_form").hasClass("error")) {
			isValid = false;
		//	this.ajax_element_update = false;
		} else {
			for (var i=0; i < formData.length; i++) {
		        if (formData[i].value) {
		        	//alert(formData[i].name);
		            if(formData[i].name == 'update_element'){
		            //	alert(formData[i].value);
		            	 this.ajax_element_update = formData[i].value;
		            //	alert(mw.comments. ajax_element_update);
		            }


		            if(formData[i].name == 'hide_element'){
		            	$(formData[i].value).fadeOut();
		            }
		            
		            if(formData[i].name == 'show_element'){
		            	$(formData[i].value).fadeIn();
		            }
		            
		           // return false; 
		        } 
		    }
			

		}

		return isValid;
	}

	this._afterSend = function(responseText, statusText, xhr, $form) {
	//	alert( this.ajax_element_update);
		                    eventlistener = 'onAfterComment';
		mw.comments.getComments($form, $update_element_selector = this.ajax_element_update);
	}

	/* ~~~ public methods ~~~ */

	this.postComment = function(form) {

		var requestOptions = {
			url : 'http://newsletter.leadersrules.com/api/comments/' + 'comments_post',
			clearForm : false,
			async : false,
			type : 'post',
			data: form.fieldSerialize(),
			beforeSubmit : this._beforeSend,
			success : this._afterSend
		};

		form.ajaxSubmit(requestOptions);
		return false;
	};
 

	this.getComments = function(form) {
 
		 
		
		$upd =($update_element_selector);
		//alert($upd);
		var requestOptions = {
				url : 'http://newsletter.leadersrules.com/api/comments/' + 'comments_list',
				resetForm : true,
				async : false,
				type : 'post',
			//	data: form.fieldSerialize(),
				success: function(resp){
			$($upd).html(resp);
			
		     //alert( "Data Saved: " + resp );
		   }
			};

			form.ajaxSubmit(requestOptions);
			return false;
 
	};

}


			  mw.ready(".ajax_comment_form", function(){
		         $(this).submit(function(){
                      if($(this).isValid()){
                          mw.comments.postComment($(this));
  					  }
      				  return false;
		         })
			  });

$(document).ready(function() {
			
			     $(window).load(function(){

			     })




			
			

			
			
			
			

			
			
			
			

			
			

			
			$('.commentForm').submit(function(){

                if($(this).isValid()){
                  mw.comments.postComment($(this), $(this).find(
                  		"input[name='to_table']").val(), $(this).find(
                  		"input[name='to_table_id']").val(), $(this)
                  		.find("input[name='update_element']").val());
                  $(this).fadeOut();

                  $(this).find('.commentFormSuccess').fadeIn();
                  location.reload(true);



                }
                else{

                }

                return false;
			});

			
		});




mw.comments.post = function($form_selector, $callback) {
	$data = ($($form_selector).serialize());

	$.ajax( {
		type : "POST",
		url : "http://newsletter.leadersrules.com/api/comments/comments_post",
		data : $data,
		dataType: 'json',
		success : function(msg) {
			//alert("Data: " + msg);
		 // $('.cart_items_qty').html(msg);
 
		if (typeof  $callback == 'function') {
			$callback.call(this, msg);
		} else {
			$($callback).fadeOut();
		}
		 
		
		
		
			
		}
	});

}






mw.comments.del = function(id, hide_element_or_callback) {
	var answer = confirm("Are you sure you want to delete this comment?");

	if (answer) {

		$.post('http://newsletter.leadersrules.com/api/comments/delete', {
			id : id
		}, function(response) {
			if (response.indexOf('yes')!=-1) {
				if (typeof (hide_element_or_callback) == 'function') {
					hide_element_or_callback.call(this);
				} else {
					$(hide_element_or_callback).fadeOut();
				}
			} else {
				alert(response);
			}
		});

	}

}



 // File: test.js 




 // File: _mw_extra.js 



var css = document.createElement("link");
css.rel = "stylesheet";
css.type = "text/css";
css.href = "http://newsletter.leadersrules.com//system/application/views/admin/static/css/api.css";

document.getElementsByTagName("head")[0].appendChild(css);



window.mw_forms = window.mw_forms ? window.mw_forms : {};
mw_forms = window.mw_forms;


mw_forms.make_fields = function(){
	
	
	
	
//	
//	 $( ".mw_slider_generated" ).slider( "destroy" );
//	 $( ".mw_slider_generated" ).remove();
//$( ".mw_option_slider" ).each(function() {
//		var $input = $(this);
//		var $slider = $('<div class="mw_slider_generated" for="' + $input.attr('name') + '" mw_slider_name="' + $input.attr('name') + '"></div>');
//		//var step = $input.attr('step');
//		$what = $input.attr('name');
//		$input.addClass('mw_slider_value');
//		$input.attr('for', $what);
//		$inputv = $input.val();
//		
//		$input_min = $input.attr('input_min');
//		$input_max = $input.attr('input_max');
//		
//		$input.before($slider);
//		//$input.after($slider);
//		
//		var $inputv = $(this).val();
//		if($inputv == undefined || $inputv == ''){
//			
//		$min = 1;
//		$max = 500;
//		 $value1 = 0;
//		
//		
//		} else { 
//		
//		$min = 1;
//		$max = 3 * parseInt($inputv);
//		$value1 =  parseInt($inputv);
//		
//		}
//	 
//
//		$slider.slider({
//			//min: $input.attr('min'),
//			//max: $input.attr('max'),
//
//			
//			min: $min,
//			//max:100,
//			max:  $max,
//			value: $value1,
//			step: 1,
//			stop: function(e, ui) {
//				//alert(ui.value);
//				//alert($(this).attr('for'));
//				
//			 
//				
//				$what = $input.attr('name');
//				
//			 
//				 
//				 
//				 
//				 $('.mw_option_slider[name="'+$input.attr('name')+'"]').val(ui.value);
//				 $('.mw_option_slider[name="'+$input.attr('name')+'"]').change();
//				//  mw_html_tag_editor_apply_styles()
//	 
//				 
//				 
//				 
//				// height: auto;
//
//				 
//				 
//				//alert($(this).val());
//				//$(this).val(ui.value);
//			}
//		});
//	});
	
	
	
	
	
	//alert('12344');
	
	
	
	
	$(".mw_option_field").not('.mw_option_field_parsed').each(function(){
		$(this).addClass('mw_option_field_parsed');
		
		
		
		
			 
			 	 
			 
			
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
//		
//		$(this).blur(function() {
//			var refresh_modules11 =  this.getAttribute("refresh_modules");
//			if(refresh_modules11 != undefined && refresh_modules11 != ''){
//				refresh_modules11 = refresh_modules11.toString()
//				
////alert(refresh_modules11);
//				if(window.mw.reload_module != undefined){
//					window.mw.reload_module(refresh_modules11);
//				}
//				
//				if(parent.mw.reload_module != undefined){
//					parent.mw.reload_module(refresh_modules11);
//				}
//
//			/*		*/
//				
//				
//				
//				
//			}
//			 
//		});
		
		
		
		
		 
		$(this).change(function() {
			 //alert('Handler for .change() called.');
			//http://newsletter.leadersrules.com/api/content/save_option			//var refresh_modules11 =  $(this).attr('name');
		//	alert(refresh_modules11);
			
			
			
			
			
			 var refresh_modules11 =  this.getAttribute("refresh_modules");
			
			// alert(refresh_modules11);
			
			
			
			
			$.ajax({
				  
				  type: "POST",
				   url: "http://newsletter.leadersrules.com/api/content/save_option",
				   data: ({
					   
					   option_key : $(this).attr('name'),
					   option_group : $(this).attr('option_group'),
					   option_value : $(this).val()
					   
				   
				   }),


				  success: function(){
				if(mw != undefined && mw.reload_module != undefined){
				mw.reload_module($(this).attr('option_group'));
				}
 
				
				
				if(refresh_modules11 != undefined && refresh_modules11 != ''){
					refresh_modules11 = refresh_modules11.toString()
					
//alert(refresh_modules11);
					if(window.mw.reload_module != undefined){
						window.mw.reload_module(refresh_modules11);
					}
					
					if(parent.mw.reload_module != undefined){
						parent.mw.reload_module(refresh_modules11);
					}

				/*		*/
					
					
					
					
				}
				
				  //  $(this).addClass("done");
				  }
				});
			
			
			
			});
		
		
	 		/*$(this).css({
	 			 'backgroud-color': 'pink',
        	    'width': 20,
        	    'height': 20   

        	    
        	});*/
		 
	});
	
	
}

$(document).ready(function(){
	//mw_forms.make_fields();
    });

//mw.ready(".mw_option_field", mw_forms.make_fields);



// used on editmode and in admin



function isEmpty(obj) {
    for(var prop in obj) {
        if(obj.hasOwnProperty(prop))
            return false;
    }

    return true;
}
$.fn.insertAtCaret = function (myValue) {
	  return this.each(function(){
	  //IE support
	  if (document.selection) {
	    this.focus();
	    sel = document.selection.createRange();
	    sel.text = myValue;
	    this.focus();
	  }
	  //MOZILLA / NETSCAPE support
	  else if (this.selectionStart || this.selectionStart == '0') {
	    var startPos = this.selectionStart;
	    var endPos = this.selectionEnd;
	    var scrollTop = this.scrollTop;
	    this.value = this.value.substring(0, startPos)+ myValue+ this.value.substring(endPos,this.value.length);
	    this.focus();
	    this.selectionStart = startPos + myValue.length;
	    this.selectionEnd = startPos + myValue.length;
	    this.scrollTop = scrollTop;
	  } else {
	    this.value += myValue;
	    this.focus();
	  }
	  });
	};
	
	$.fn.insertAtCaret = function (myValue) {
		return this.each(function(){
				//IE support
				if (document.selection) {
						this.focus();
						sel = document.selection.createRange();
						sel.text = myValue;
						this.focus();
				}
				//MOZILLA / NETSCAPE support
				else if (this.selectionStart || this.selectionStart == '0') {
						var startPos = this.selectionStart;
						var endPos = this.selectionEnd;
						var scrollTop = this.scrollTop;
						this.value = this.value.substring(0, startPos)+ myValue+ this.value.substring(endPos,this.value.length);
						this.focus();
						this.selectionStart = startPos + myValue.length;
						this.selectionEnd = startPos + myValue.length;
						this.scrollTop = scrollTop;
				} else {
						this.value += myValue;
						this.focus();
				}
		});
	};
	
	
	function mw_insertHtmlAtCursor(html) {
	    var range, node;
	    if (window.getSelection && window.getSelection().getRangeAt) {
	        range = window.getSelection().getRangeAt(0);
	        node = range.createContextualFragment(html);
	        range.insertNode(node);
	    } else if (document.selection && document.selection.createRange) {
	        document.selection.createRange().pasteHTML(html);
	    }
	}
	
	
	function mw_insertNodeAtCursor(node) {
	    var range, html;
	    if (window.getSelection && window.getSelection().getRangeAt) {
	        range = window.getSelection().getRangeAt(0);
	        range.insertNode(node);
	    } else if (document.selection && document.selection.createRange) {
	        range = document.selection.createRange();
	        html = (node.nodeType == 3) ? node.data : node.innerHTML;
	        range.pasteHTML(html);
	    }
	}
	
	
	jQuery.expr[':'].parents = function(a,i,m){
	    return jQuery(a).parents(m[3]).length < 1;
	};

	
	$.fn.hasAncestor = function(a) {
	    return this.filter(function() {
	        return !!$(this).closest(a).length;
	    });
	};


	
	
	/*
	 * jQuery outside events - v1.1 - 3/16/2010
	 * http://benalman.com/projects/jquery-outside-events-plugin/
	 * 
	 * Copyright (c) 2010 "Cowboy" Ben Alman
	 * Dual licensed under the MIT and GPL licenses.
	 * http://benalman.com/about/license/
	 */
	(function($,c,b){$.map("click dblclick mousemove mousedown mouseup mouseover mouseout change select submit keydown keypress keyup".split(" "),function(d){a(d)});a("focusin","focus"+b);a("focusout","blur"+b);$.addOutsideEvent=a;function a(g,e){e=e||g+b;var d=$(),h=g+"."+e+"-special-event";$.event.special[e]={setup:function(){d=d.add(this);if(d.length===1){$(c).bind(h,f)}},teardown:function(){d=d.not(this);if(d.length===0){$(c).unbind(h)}},add:function(i){var j=i.handler;i.handler=function(l,k){l.target=k;j.apply(this,arguments)}}};function f(i){$(d).each(function(){var j=$(this);if(this!==i.target&&!j.has(i.target).length){j.triggerHandler(e,[i.target])}})}}})(jQuery,document,"outside");
	
	$.event.special.tripleclick = {

		    setup: function(data, namespaces) {
		        var elem = this, $elem = jQuery(elem);
		        $elem.bind('click', jQuery.event.special.tripleclick.handler);
		    },

		    teardown: function(namespaces) {
		        var elem = this, $elem = jQuery(elem);
		        $elem.unbind('click', jQuery.event.special.tripleclick.handler)
		    },

		    handler: function(event) {
		        var elem = this, $elem = jQuery(elem), clicks = $elem.data('clicks') || 0;
		        clicks += 1;
		        if ( clicks === 3 ) {
		            clicks = 0;

		            // set event type to "tripleclick"
		            event.type = "tripleclick";

		            // let jQuery handle the triggering of "tripleclick" event handlers
		            jQuery.event.handle.apply(this, arguments)
		        }
		        $elem.data('clicks', clicks);
		    }

		};


	(function($) {
	    $.fn.getAttributes = function() {
	        var attributes = {}; 

	        if(!this.length)
	            return this;

	        $.each(this[0].attributes, function(index, attr) {
	            attributes[attr.name] = attr.value;
	        }); 

	        return attributes;
	    }
	})(jQuery);
	
	
	
	
	
 
	function setCaretAfter(el) {
	    var sel, range;
	    if (window.getSelection && document.createRange) {
	        range = document.createRange();
	        range.setStartAfter(el);
	        range.collapse(true);
	        sel = window.getSelection(); 
	        sel.removeAllRanges();
	        sel.addRange(range);
	    } else if (document.body.createTextRange) {
	        range = document.body.createTextRange();
	        range.moveToElementText(el);
	        range.collapse(false);
	        range.select();
	    }
	}
	
	
	function addClass(element, value) {
		if(!element.className) {
			element.className = value;
		} else {
			newClassName = element.className;
			newClassName+= " ";
			newClassName+= value;
			element.className = newClassName;
		}
	}
	
	// jquery_trigger_ready.js
	// this function is added to jQuery, it allows access to the readylist
	// it works for jQuery 1.3.2, it might break on future versions
	 
	
	/**
	* hoverIntent is similar to jQuery's built-in "hover" function except that
	* instead of firing the onMouseOver event immediately, hoverIntent checks
	* to see if the user's mouse has slowed down (beneath the sensitivity
	* threshold) before firing the onMouseOver event.
	* 
	* hoverIntent r6 // 2011.02.26 // jQuery 1.5.1+
	* <http://cherne.net/brian/resources/jquery.hoverIntent.html>
	* 
	* hoverIntent is currently available for use in all personal or commercial 
	* projects under both MIT and GPL licenses. This means that you can choose 
	* the license that best suits your project, and use it accordingly.
	* 
	* // basic usage (just like .hover) receives onMouseOver and onMouseOut functions
	* $("ul li").hoverIntent( showNav , hideNav );
	* 
	* // advanced usage receives configuration object only
	* $("ul li").hoverIntent({
	*	sensitivity: 7, // number = sensitivity threshold (must be 1 or higher)
	*	interval: 100,   // number = milliseconds of polling interval
	*	over: showNav,  // function = onMouseOver callback (required)
	*	timeout: 0,   // number = milliseconds delay before onMouseOut function call
	*	out: hideNav    // function = onMouseOut callback (required)
	* });
	* 
	* @param  f  onMouseOver function || An object with configuration options
	* @param  g  onMouseOut function  || Nothing (use configuration options object)
	* @author    Brian Cherne brian(at)cherne(dot)net
	*/
	(function($) {
		$.fn.hoverIntent = function(f,g) {
			// default configuration options
			var cfg = {
				sensitivity: 7,
				interval: 100,
				timeout: 0
			};
			// override configuration options with user supplied object
			cfg = $.extend(cfg, g ? { over: f, out: g } : f );

			// instantiate variables
			// cX, cY = current X and Y position of mouse, updated by mousemove event
			// pX, pY = previous X and Y position of mouse, set by mouseover and polling interval
			var cX, cY, pX, pY;

			// A private function for getting mouse position
			var track = function(ev) {
				cX = ev.pageX;
				cY = ev.pageY;
			};

			// A private function for comparing current and previous mouse position
			var compare = function(ev,ob) {
				ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
				// compare mouse positions to see if they've crossed the threshold
				if ( ( Math.abs(pX-cX) + Math.abs(pY-cY) ) < cfg.sensitivity ) {
					$(ob).unbind("mousemove",track);
					// set hoverIntent state to true (so mouseOut can be called)
					ob.hoverIntent_s = 1;
					return cfg.over.apply(ob,[ev]);
				} else {
					// set previous coordinates for next time
					pX = cX; pY = cY;
					// use self-calling timeout, guarantees intervals are spaced out properly (avoids JavaScript timer bugs)
					ob.hoverIntent_t = setTimeout( function(){compare(ev, ob);} , cfg.interval );
				}
			};

			// A private function for delaying the mouseOut function
			var delay = function(ev,ob) {
				ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
				ob.hoverIntent_s = 0;
				return cfg.out.apply(ob,[ev]);
			};

			// A private function for handling mouse 'hovering'
			var handleHover = function(e) {
				// copy objects to be passed into t (required for event object to be passed in IE)
				var ev = jQuery.extend({},e);
				var ob = this;

				// cancel hoverIntent timer if it exists
				if (ob.hoverIntent_t) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); }

				// if e.type == "mouseenter"
				if (e.type == "mouseenter") {
					// set "previous" X and Y position based on initial entry point
					pX = ev.pageX; pY = ev.pageY;
					// update "current" X and Y position based on mousemove
					$(ob).bind("mousemove",track);
					// start polling interval (self-calling timeout) to compare mouse coordinates over time
					if (ob.hoverIntent_s != 1) { ob.hoverIntent_t = setTimeout( function(){compare(ev,ob);} , cfg.interval );}

				// else e.type == "mouseleave"
				} else {
					// unbind expensive mousemove event
					$(ob).unbind("mousemove",track);
					// if hoverIntent state is true, then call the mouseOut function after the specified delay
					if (ob.hoverIntent_s == 1) { ob.hoverIntent_t = setTimeout( function(){delay(ev,ob);} , cfg.timeout );}
				}
			};

			// bind the function to the two event listeners
			return this.bind('mouseenter',handleHover).bind('mouseleave',handleHover);
		};
	})(jQuery);
	
	 
	
	
	
	
 
	
	
	function RGBtoHex(R,G,B) {return toHex(R)+toHex(G)+toHex(B)}
	function toHex(N) {
	 if (N==null) return "00";
	 N=parseInt(N); if (N==0 || isNaN(N)) return "00";
	 N=Math.max(0,N); N=Math.min(N,255); N=Math.round(N);
	 return "0123456789ABCDEF".charAt((N-N%16)/16)
	      + "0123456789ABCDEF".charAt(N%16);
	}
	
	
	
	    
	// VALIDATE


	//Change log: added .require-equal(must add an attribute: equalto="some_word")

	//check empty
	function require(the_form){
	    the_form.find(".required").each(function(){
	          if($(this).attr("type")!="checkbox"){
	              if($(this).val()=="" ||  $(this).val()==$(this).attr("default")){
	                $(this).parent().addClass("error");
	              }
	              else{
	                $(this).parent().removeClass("error");
	              }
	          }
	          else{
	            if($(this).attr("checked")==""){
	              $(this).parent().addClass("error");
	            }
	          }
	    });
	}

	//check email
	function checkMail(the_form){
	      the_form.find(".required-email").each(function(){
	          var thismail = $(this);
	          var thismailval = $(this).val();
	          var regexmail = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/;

	          if (regexmail.test(thismailval)){
	              thismail.parent().removeClass("error");
	          }
	          else{
	             thismail.parent().addClass("error");
	          }
	    })
	}

	function checkNumber(the_form){
	      the_form.find(".required-number").each(function(){
	          var thisnumber = $(this);
	          var thismailval = $(this).val();
	          var regexmail = /^[0-9]+$/;

	          if (regexmail.test(thismailval)){
	              thisnumber.parent().removeClass("error");
	          }
	          else{
	             thisnumber.parent().addClass("error");
	          }
	    })
	}
	function checkEqual(the_form){
	      the_form.find(".required-equal").each(function(){
	          var equalto = $(this).attr("equalto");
	          val1 = $(this).parents("form").find("[equalto='" + equalto + "']").eq(0).val();
	          val2 = $(this).parents("form").find("[equalto='" + equalto + "']").eq(1).val();
	          if(val1!=val2 || val1=='' || val2==''){
	              $(this).parents("form").find("[equalto='" + equalto + "']").parent().addClass("error");
	          }
	          else{
	              $(this).parents("form").find("[equalto='" + equalto + "']").parent().removeClass("error");
	          }
	      });
	}
	(function($) {
		$.fn.validate = function(callback) {
	        $(this).each(function(){
	            $(this).submit(function(){
	                  oform = $(this);
	                  var valid=true;
	                  require(oform);
	                  checkMail(oform);
	                  checkNumber(oform);
	                  checkEqual(oform);

	                  //Final check
	                  if(oform.find(".error").length>0){
	                      oform.addClass("error");
	                      valid=false;
	                  }
	                  else{
	                      oform.removeClass("error");
	                      valid=true;
	                  }
	                  oform.addClass("submitet");

	                  if(valid==true && callback!=undefined && typeof callback == 'function'){
	                      callback.call(this);
	                      return false;
	                  }
	                  else{
	                     return valid;
	                  }

	            });
	            $(this).find(".required").bind("keyup blur change mouseup", function(){
	                if($(this).parents("form").hasClass("submitet")){
	                  if($(this).val()=="" || $(this).val()==$(this).attr("default")){
	                    $(this).parent().addClass("error");
	                  }
	                  else{
	                    $(this).parent().removeClass("error");
	                  }
	                }
	            });
	            $(this).find(".required-equal").bind("keyup blur change mouseup", function(){
	              if($(this).parents("form").hasClass("submitet")){
	                  var equalto = $(this).attr("equalto");
	                  val1 = $(this).parents("form").find("[equalto='" + equalto + "']").eq(0).val();
	                  val2 = $(this).parents("form").find("[equalto='" + equalto + "']").eq(1).val();
	                  if(val1!=val2 || val1=='' || val2==''){
	                      $(this).parents("form").find("[equalto='" + equalto + "']").parent().addClass("error");
	                  }
	                  else{
	                      $(this).parents("form").find("[equalto='" + equalto + "']").parent().removeClass("error");
	                  }
	              }
	            });

	            $(this).find(".required-email").bind("keyup blur", function(){
	                if($(this).parents("form").hasClass("submitet")){
	                  var thismail = $(this);
	                  var thismailval = $(this).val();
	                  var regexmail = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/;
	                  if (regexmail.test(thismailval)){
	                      thismail.parent().removeClass("error");
	                  }
	                  else{
	                     thismail.parent().addClass("error");
	                  }
	                }
	            });

	            $(this).find(".required-number").bind("keyup blur", function(){
	                if($(this).parents("form").hasClass("submitet")){
	                  var thisnumber = $(this);
	                  var thisnumberval = $(this).val();
	                  var regexmail = /^[0-9]+$/;
	                  if (regexmail.test(thisnumberval)){
	                      thisnumber.parent().removeClass("error");
	                  }
	                  else{
	                     thisnumber.parent().addClass("error");
	                  }
	                }
	            });
	        });
	    };
	})(jQuery);

	(function($) {
		$.fn.isValid = function(){
		  var valid=true;
		  $(this).each(function(){
	        oform = $(this);
	        require(oform);
	        checkMail(oform);
	        checkNumber(oform);
	        checkEqual(oform);
	        if(oform.find(".error").length>0){
	            oform.addClass("error");
	            valid=false;
	        }
	        else{
	            oform.removeClass("error");
	            valid=true;
	        }
	        oform.addClass("submitet");
		  });
	      return valid;
	    };
	})(jQuery);


	function findElPos(obj) {
	    var curleft = curtop = 0;
	    if (obj.offsetParent) {
	        curleft = obj.offsetLeft
	        curtop = obj.offsetTop
	        while (obj = obj.offsetParent) {
	            curleft += obj.offsetLeft
	            curtop += obj.offsetTop
	        }
	    }
	    return [curleft,curtop];
	}

	
	
	
	
	
	jQuery.fn.getPos = function(){
        var o = this[0];
        var left = 0, top = 0, parentNode = null, offsetParent = null;
        offsetParent = o.offsetParent;
        var original = o;
        var el = o;
        while (el.parentNode != null) {
            el = el.parentNode;
            if (el.offsetParent != null) {
                var considerScroll = true;
                if (window.opera) {
                    if (el == original.parentNode || el.nodeName == "TR") {
                        considerScroll = false;
                    }
                }
                if (considerScroll) {
                    if (el.scrollTop && el.scrollTop > 0) {
                        top -= el.scrollTop;
                    }
                    if (el.scrollLeft && el.scrollLeft > 0) {
                        left -= el.scrollLeft;
                    }
                }
            }            
            if (el == offsetParent) {
                left += o.offsetLeft;
                if (el.clientLeft && el.nodeName != "TABLE") {
                    left += el.clientLeft;
                }
                top += o.offsetTop;
                if (el.clientTop && el.nodeName != "TABLE") {
                    top += el.clientTop;
                }
                o = el;
                if (o.offsetParent == null) {
                    if (o.offsetLeft) {
                        left += o.offsetLeft;
                    }
                    if (o.offsetTop) {
                        top += o.offsetTop;
                    }
                }
                offsetParent = o.offsetParent;
            }
        }
        return {
            left: left,
            top: top
        };
    };


 // File: cart.js 

mw.cart = {};

mw.cart.add = function($form_selector, $callback) {
	$data = ($($form_selector).serialize());

	$.ajax( {
		type : "POST",
		url : "http://newsletter.leadersrules.com/api/cart/add",
		data : $data,
		success : function(msg) {
			//alert("Data: " + msg);
		 // $('.cart_items_qty').html(msg);
		mw.cart.update_info();
		
		
		if (typeof  $callback == 'function') {
			$callback.call(this);
		} else {
			$($callback).fadeOut();
		}
		
		
		
		
			
		}
	});

}

mw.cart.remove_item = function($item_id_in_cart) {

	var answer = confirm("Are you sure you want to remove this item from your cart?")
	if (answer) {

		$.ajax( {
					type : "POST",
					async : false,
					url : "http://newsletter.leadersrules.com/api/cart/remove_item",
					data : "id=" + $item_id_in_cart,
					success : function(data) {
						$.post(
										"http://newsletter.leadersrules.com/ajax_helpers/cart_itemsGetQty",
										{
											name : "John",
											time : "2pm"
										},
										function(data) {
											data = parseInt(data);
											if (data == 0) {

											} else {
												$(
														'#cart_item_row_' + $item_id_in_cart)
														.fadeOut();
											}
										});
						mw.cart.update_info();
					}
				});

	} else {

	}

}

mw.cart.modify_item_properties = function($item_id_in_cart, $propery_name,$new_value) {

	$.ajax( {
		type : "POST",
		url : "http://newsletter.leadersrules.com/api/cart/modify_item_properties",
		data : "id=" + $item_id_in_cart + "&propery_name=" + $propery_name
				+ "&new_value=" + $new_value,
		async : false,
		success : function(data) {
		mw.cart.update_info();
		}
	});
}


mw.cart.update_info = function() {
	
	$.ajax( {
		type : "POST",
		dataType: 'json',
		url : "http://newsletter.leadersrules.com/api/cart/order_info",
		//data : $data,
		success : function(msg) {
			//alert("Data: " + msg.qty);
		  $('.cart_items_qty').html(msg.qty);
		  $('.cart_items_total').html(msg.total);
			
		}
	});
	
	
	
}


mw.cart.complete_order = function($form_selector, $hide_selector, $show_selector) {
	$data = ($($form_selector).serialize());

	// / alert($data);

	$.ajax( {
		type : "POST",
		url : "http://newsletter.leadersrules.com/api/cart/complete_order",
		data : $data,
		async : false,
		success : function(data) {
			//alert(data);
		  if($hide_selector != undefined ){
			  
			  $($hide_selector).fadeOut();
			   
		  }
		  
		  
  if($show_selector != undefined ){
			  
			  $($show_selector).fadeIn();
			   
		  }
  
  mw.cart.update_info();
		  
		  
		  
		  
		}
	});
}



mw.cart.delete_order = function($id, $selector_to_hide) {
 
	var answer = confirm("WARNING: There is no turning back! Are you sure you want to delete this order? ")
	if (answer) {
		// / alert($data);
	
		$.ajax( {
			type : "POST",
			url : "http://newsletter.leadersrules.com/api/cart/delete_order",
			data : "id=" + $id ,
			async : true,
			success : function(data) {
			 
			  if($selector_to_hide != undefined ){
				  
				  $($selector_to_hide).fadeOut();
				   
			  }
			
			
			}
		});
	}
}







mw.cart.check_promo_code = function($code) {
	
	
	if($code == undefined){
		var code_check = $('#the_promo_code_input').val();
		
	} else {
		var code_check = $code
			
	}
	
	
	$.ajax({
		   type: "POST",
		   url: "http://newsletter.leadersrules.com/api/cart/get_promo_code",
		   data: "code=" + code_check,
		   dataType: 'json',
		   success: function(msg){
		  if(msg.promo_code != undefined){
		 $('#the_promo_code_input').val(msg.promo_code);
			  $('#the_promo_code_status').show();
			  $('#the_promo_code_status').html(msg.description);
			  mw.cart.update_info();
		  }
		     
		     
		   }
		 });

 
	
}





















 // File: box.js 

mw.id = function(){
  return Math.floor(Math.random()*99999);
}

mw.modal={
  create:function(content, height){
    var modal_content = "";
    var modal_obj = "";
    if(typeof content == 'object'){
      var modal_tag_id = false;
      if($(document.body).has(content).length>0){
        modal_tag_id = 'x_' + mw.id();
        var content_obj = $(content).clone(true).css({display:"block",visibility:"visible"});
        modal_old = $(content);
		//alert(modal_old);
		
		
        $(content).after('<mwmodal class="' + modal_tag_id + '" />');
        $(content).destroy();
      }
      else{
         var content_obj = content;
      }
    }
    else{
      //var modal_content = content;
      var modal_content = '';
      var content_obj = content;
    }
    var modal_source = ''
    +'<div class="mw_modal_box">'
       + '<div class="mw_modal_main" style="height:' + height + 'px">'
        + '<div class="mw_modal_header radius_t">'
            + '<h2><!-- Title Comes Here --></h2>'
			 + '<span class="mw_modal_buttons"></span>'
            + '<span class="mw_modalclose" title="Close">Close</span>'
        + '</div>'
        + '<div class="mw_modal_content_box">'
            + modal_content
        + '</div>' 
       + '</div>'
    +'</div>';
    var modaler = document.createElement('div');
    if(modal_tag_id!=false){
       modaler.id = modal_tag_id;
    }
	// alert(content_obj);
    modaler.innerHTML = modal_source;
    modaler.className = 'modal_data';
    $(modaler).find(".mw_modal_content_box").html(content_obj);

    return modaler;
  },
  
  overlay:function(color){
    if($("#mw_overlay").length==0){
          var overlay = document.createElement('div');
    overlay.id = 'mw_overlay';
      if(color==undefined){
          overlay.style.backgroundColor = '#000000';
          overlay.style.display = 'block';
      }
      else{
          overlay.style.backgroundColor = color;
          overlay.style.display = 'block';
      }
    }
    document.body.appendChild(overlay);
  },
  init:function(obj){
    var id = isobj(obj.id)?obj.id:mw.id();
	$(".mw_modal").show();
    if($("#mw_modal_" + id).length==0){

      if(typeof obj == 'object' ){
          var modal = document.createElement('div');
          if(isobj(obj.id)){
            var id = obj.id;
          }
          else{
            var id = mw.id();
          }
          modal.id = 'mw_modal_' + id;
          obj.width = !isobj(obj.width)?400:obj.width;
          obj.height = !isobj(obj.height)?250:obj.height;
          obj.title = !isobj(obj.title)?'':obj.title;
		  obj.buttons = !isobj(obj.buttons)?'':obj.buttons;



          modal.appendChild(mw.modal.create(obj.html, obj.height));
          modal.style.width = obj.width + 'px';
          if(!isobj(obj.customPosition)){
            var skin = !isobj(obj.skin)?'':obj.skin;
            modal.className='mw_modal mw_modalcentered ' + skin;
            if(obj.height<$(window).height()){
              modal.style.top = $(window).scrollTop() + ($(window).height())/2-obj.height/2 + 'px';
            }
            else{
               modal.style.top = ($(window).scrollTop() + 10) + 'px';
            }

            modal.style.left = $(window).width()/2 - obj.width /2 + 'px';
          }
          else{
            var skin = !isobj(obj.skin)?'':obj.skin;
            modal.className='mw_modal ' + skin;
            modal.style.top = obj.customPosition.top + 'px';
            modal.style.left = obj.customPosition.left != 'center'?obj.customPosition.left + 'px':$(window).width()/2 - obj.width/2 + 'px';
          }
          $(modal).find(".mw_modal_buttons").html(obj.buttons);
		  
		            $(modal).find("h2").html(obj.title);

		  
		  
          $(modal).find(".mw_modalclose").click(function(){
               if(isobj(obj.onclose) && typeof obj.onclose=='function'){
             obj.onclose.call(modal);
          }
		  
            mw.modal.close(id);
          });
          document.body.appendChild(modal);
          if(isobj(obj.oninit) && typeof obj.oninit=='function'){
             obj.oninit.call(modal);
          }
		  
		//   if(isobj(obj.onclose) && typeof obj.onclose=='function'){
//             obj.onclose.call(modal);
//          }
		  
		  
		  
		  
          if(obj.overlay==true){
            mw.modal.overlay();
          }
          modal.onmousedown = function(){
            if($(".mw_modal").length>1){
              this.style.zIndex = mw.modal.zindex();
            }
          }
          $(modal).draggable({handle:'.mw_modal_header', iframeFix:true});
          return modal;
      }
    }
  },
  zindex:function(){
     var mw_zindex = 0;
     $(".mw_modal").each(function(){
        var zindex = parseFloat($(this).css("zIndex"));
        if(zindex>mw_zindex){mw_zindex = zindex}
      });
      return mw_zindex+1;
  },
  close:function(id){
	  
 if(isobj(id)){
        
     $("#mw_modal_"+id).remove();  // 
    }
    else{
  //    $(".mw_modal").hide();
    }
	$(".mw_modal").remove();
    $("#mw_overlay").remove()
	
	
	
	
	   
    //if(isobj(id)){
//        if($("#mw_modal_"+id).find(".modal_data").attr("id") !="undefined" && $("#mw_modal_"+id).find(".modal_data").attr("id") != ""){
//          var el = $("#mw_modal_"+id);
//          el.find(".mw_modalclose").remove();
//          var clone = el.find(".mw_modal_main :first").clone(true);
//          clone.hide();
//          var dataid = el.find(".modal_data").attr("id");
//          $("." + dataid).replaceWith(clone);
//        }
//        $("#mw_modal_"+id).remove();
//    }
//    else{
//      $(".mw_modal").remove();
//    }
//    $("#mw_overlay").remove()
  },
  confirm:function(obj){
    var confirm = mw.modal.init({
      html:'<table width="400" height="150"><tr><td style="text-align:center">'+obj.html + '</td></tr></table><div class="c"></div><div class="okCancel"><a href="javascript:;" class="mw_confirm_yes">OK</a><a href="javascript:;" class="mw_confirm_no">Cancel</a></div>',
      oninit:function(){
        var el = this;
        $(this).find(".mw_confirm_yes").click(function(){
            mw.modal.close(obj.id);
            if(isobj(obj.yes)){
                obj.yes.call(this);
            }

        });
        $(this).find(".mw_confirm_no").click(function(){
            mw.modal.close(obj.id);
             if(isobj(obj.no)){
               obj.no.call(this);
             }

        });
        $(this).find(".mw_modalclose").mouseup(function(){
          mw.modal.close(obj.id);
             if(isobj(obj.no)){
               obj.no.call(this);
             }
        });
      },
      width:400,
      height:200,
      id:isobj(obj.id)?obj.id:mw.id()
    })
  },
  alert:function(obj){
      mw.modal.init({
      html:'<table width="380" height="130"><tr><td style="text-align:center">'+obj + '</td></tr></table><div class="c"></div><div class="okCancel"><a href="javascript:;" class="mw_confirm_yes">OK</a></div>',
      oninit:function(){
        el = this;
        $(this).find(".mw_confirm_yes").click(function(){
            mw.modal.close(obj.id);
        });
      },
      width:400,
      height:200,
      id:'mw_Alert'
    })
  },
  iframe:function(obj){
    var frame = document.createElement('iframe');
    frame.src = obj.src;
    frame.frameBorder = 0;
	frame.name = isobj(obj.id)?obj.id:mw.id();
	frame.id = isobj(obj.id)?obj.id:mw.id();
    frame.scrolling='auto';
    var width = isobj(obj.width)?(obj.width-20):380;
    var height = isobj(obj.height)?(obj.height-20):230;
    frame.style.width = width + 'px';
    frame.style.height = height + 'px';
	
	
	
	
	
    mw.modal.init({
        html:frame,
        width:isobj(obj.width)?obj.width:400,
        height:isobj(obj.height)?obj.height:250,
		 title:isobj(obj.title)?obj.title:'',
		 onclose:isobj(obj.onclose)?obj.onclose:'',
		 
		  buttons:isobj(obj.buttons)?obj.buttons:'',
		 
		 
        id:isobj(obj.id)?obj.id:mw.id()
		
    })
  },
  context:function(obj){
     var edit_pop =  mw.modal.init({
        html:obj.html,
        width:isobj(obj.width)?obj.width:200,
        height:isobj(obj.height)?obj.height:150,
        id:isobj(obj.id)?obj.id:mw.id(),
        customPosition:{
          top:obj.event.pageY,
          left:obj.event.pageX + 5
        },
        oninit:isobj(obj.oninit)?obj.oninit:''
     });
      $(obj.elem)[0].oncontextmenu = function() {
        return false;
      }
      mw.prevent(obj.event);
  }
}



isobj = function(obj){
    if( obj == undefined){
      return false;
    }
    else{return true}
}
