/**
 * @license
 * jQuery Tools 1.2.5 / Overlay Apple effect.
 *
 * NO COPYRIGHTS OR LICENSES. DO WHAT YOU LIKE.
 *
 * http://flowplayer.org/tools/overlay/apple.html
 *
 * Since: July 2009
 * Date:    Wed Sep 22 06:02:10 2010 +0000
 */
(function($) {

	// version number
	var t = $.tools.overlay,
		 w = $(window);

	// extend global configuragion with effect specific defaults
	$.extend(t.conf, {
		start: {
			top: null,
			left: null
		},

		fadeInSpeed: 'fast',
		zIndex: 9999
	});

	// utility function
	function getPosition(el) {
		var p = el.offset();
		return {
			top: p.top + el.height() / 2,
			left: p.left + el.width() / 2
		};
	}

//{{{ load

	var loadEffect = function(pos, onLoad) {

		var overlay = this.getOverlay(),
			 conf = this.getConf(),
			 trigger = this.getTrigger(),
			 self = this,
			 oWidth = overlay.outerWidth({margin:true}),
			 img = overlay.data("img"),
			 position = conf.fixed ? 'fixed' : 'absolute';


		// growing image is required.
		if (!img) {
			var bg = overlay.css("backgroundImage");

			if (!bg) {
				throw "background-image CSS property not set for overlay";
			}

			// url("bg.jpg") --> bg.jpg
			bg = bg.slice(bg.indexOf("(") + 1, bg.indexOf(")")).replace(/\"/g, "");
			overlay.css("backgroundImage", "none");

			img = $('<img src="' + bg + '"/>');
			img.css({border:0, display:'none'}).width(oWidth);
			$('body').append(img);
			overlay.data("img", img);
		}

		// initial top & left
		var itop = conf.start.top || Math.round(w.height() / 2),
			 ileft = conf.start.left || Math.round(w.width() / 2);

		if (trigger) {
			var p = getPosition(trigger);
			itop = p.top;
			ileft = p.left;
		}

		// put overlay into final position
		if (conf.fixed) {
			itop -= w.scrollTop();
			ileft -= w.scrollLeft();
		} else {
			pos.top += w.scrollTop();
			pos.left += w.scrollLeft();
		}

		// initialize background image and make it visible
		img.css({
			position: 'absolute',
			top: itop,
			left: ileft,
			width: 0,
			zIndex: conf.zIndex
		}).show();

		pos.position = position;
		overlay.css(pos);

		// begin growing
		img.animate({
			top: overlay.css("top"),
			left: overlay.css("left"),
			width: oWidth}, conf.speed, function() {

			// set close button and content over the image
			overlay.css("zIndex", conf.zIndex + 1).fadeIn(conf.fadeInSpeed, function()  {

				if (self.isOpened() && !$(this).index(overlay)) {
					onLoad.call();
				} else {
					overlay.hide();
				}
			});

		}).css("position", position);

	};
//}}}


	var closeEffect = function(onClose) {

		// variables
		var overlay = this.getOverlay().hide(),
			 conf = this.getConf(),
			 trigger = this.getTrigger(),
			 img = overlay.data("img"),

			 css = {
			 	top: conf.start.top,
			 	left: conf.start.left,
			 	width: 0
			 };

		// trigger position
		if (trigger) {$.extend(css, getPosition(trigger));}


		// change from fixed to absolute position
		if (conf.fixed) {
			img.css({position: 'absolute'})
				.animate({top: "+=" + w.scrollTop(), left: "+=" + w.scrollLeft()}, 0);
		}

		// shrink image
		img.animate(css, conf.closeSpeed, onClose);
	};


	// add overlay effect
	t.addEffect("apple", loadEffect, closeEffect);

})(jQuery);


/**
 * @license
 * jQuery Tools 1.2.5 / Expose - Dim the lights
 *
 * NO COPYRIGHTS OR LICENSES. DO WHAT YOU LIKE.
 *
 * http://flowplayer.org/tools/toolbox/expose.html
 *
 * Since: Mar 2010
 * Date:    Wed Sep 22 06:02:10 2010 +0000
 */
(function($) {

	// static constructs
	$.tools = $.tools || {version: '1.2.5'};

	var tool;

	tool = $.tools.expose = {

		conf: {
			maskId: 'exposeMask',
			loadSpeed: 'slow',
			closeSpeed: 'fast',
			closeOnClick: true,
			closeOnEsc: true,

			// css settings
			zIndex: 9998,
			opacity: 0.8,
			startOpacity: 0,
			color: '#fff',

			// callbacks
			onLoad: null,
			onClose: null
		}
	};

	/* one of the greatest headaches in the tool. finally made it */
	function viewport() {

		// the horror case
		if ($.browser.msie) {

			// if there are no scrollbars then use window.height
			var d = $(document).height(), w = $(window).height();

			return [
				window.innerWidth || 							// ie7+
				document.documentElement.clientWidth || 	// ie6
				document.body.clientWidth, 					// ie6 quirks mode
				d - w < 20 ? w : d
			];
		}

		// other well behaving browsers
		return [$(document).width(), $(document).height()];
	}

	function call(fn) {
		if (fn) {return fn.call($.mask);}
	}

	var mask, exposed, loaded, config, overlayIndex;


	$.mask = {

		load: function(conf, els) {

			// already loaded ?
			if (loaded) {return this;}

			// configuration
			if (typeof conf == 'string') {
				conf = {color: conf};
			}

			// use latest config
			conf = conf || config;

			config = conf = $.extend($.extend({}, tool.conf), conf);

			// get the mask
			mask = $("#" + conf.maskId);

			// or create it
			if (!mask.length) {
				mask = $('<div/>').attr("id", conf.maskId);
				$("body").append(mask);
			}

			// set position and dimensions
			var size = viewport();

			mask.css({
				position:'absolute',
				top: 0,
				left: 0,
				width: size[0],
				height: size[1],
				display: 'none',
				opacity: conf.startOpacity,
				zIndex: conf.zIndex
			});

			if (conf.color) {
				mask.css("backgroundColor", conf.color);
			}

			// onBeforeLoad
			if (call(conf.onBeforeLoad) === false) {
				return this;
			}

			// esc button
			if (conf.closeOnEsc) {
				$(document).bind("keydown.mask", function(e) {
					if (e.keyCode == 27) {
						$.mask.close(e);
					}
				});
			}

			// mask click closes
			if (conf.closeOnClick) {
				mask.bind("click.mask", function(e)  {
					$.mask.close(e);
				});
			}

			// resize mask when window is resized
			$(window).bind("resize.mask", function() {
				$.mask.fit();
			});

			// exposed elements
			if (els && els.length) {

				overlayIndex = els.eq(0).css("zIndex");

				// make sure element is positioned absolutely or relatively
				$.each(els, function() {
					var el = $(this);
					if (!/relative|absolute|fixed/i.test(el.css("position"))) {
						el.css("position", "relative");
					}
				});

				// make elements sit on top of the mask
				exposed = els.css({zIndex: Math.max(conf.zIndex + 1, overlayIndex == 'auto' ? 0 : overlayIndex)});
			}

			// reveal mask
			mask.css({display: 'block'}).fadeTo(conf.loadSpeed, conf.opacity, function() {
				$.mask.fit();
				call(conf.onLoad);
				loaded = "full";
			});

			loaded = true;
			return this;
		},

		close: function() {
			if (loaded) {

				// onBeforeClose
				if (call(config.onBeforeClose) === false) {return this;}

				mask.fadeOut(config.closeSpeed, function()  {
					call(config.onClose);
					if (exposed) {
						exposed.css({zIndex: overlayIndex});
					}
					loaded = false;
				});

				// unbind various event listeners
				$(document).unbind("keydown.mask");
				mask.unbind("click.mask");
				$(window).unbind("resize.mask");
			}

			return this;
		},

		fit: function() {
			if (loaded) {
				var size = viewport();
				mask.css({width: size[0], height: size[1]});
			}
		},

		getMask: function() {
			return mask;
		},

		isLoaded: function(fully) {
			return fully ? loaded == 'full' : loaded;
		},

		getConf: function() {
			return config;
		},

		getExposed: function() {
			return exposed;
		}
	};

	$.fn.mask = function(conf) {
		$.mask.load(conf);
		return this;
	};

	$.fn.expose = function(conf) {
		$.mask.load(conf, this);
		return this;
	};


})(jQuery);

function clearInputText(inputbox){
    if (inputbox.value == 'search here..')
        inputbox.value = '';
}

/**
 *Popup window function jquery. alternative to window.open
 */
(function($){
	$.fn.popupWindow = function(instanceSettings){

		return this.each(function(){

		$(this).click(function(){

		$.fn.popupWindow.defaultSettings = {
			centerBrowser:0, // center window over browser window? {1 (YES) or 0 (NO)}. overrides top and left
			centerScreen:0, // center window over entire screen? {1 (YES) or 0 (NO)}. overrides top and left
			height:500, // sets the height in pixels of the window.
			left:0, // left position when the window appears.
			location:0, // determines whether the address bar is displayed {1 (YES) or 0 (NO)}.
			menubar:0, // determines whether the menu bar is displayed {1 (YES) or 0 (NO)}.
			resizable:0, // whether the window can be resized {1 (YES) or 0 (NO)}. Can also be overloaded using resizable.
			scrollbars:0, // determines whether scrollbars appear on the window {1 (YES) or 0 (NO)}.
			status:0, // whether a status line appears at the bottom of the window {1 (YES) or 0 (NO)}.
			width:500, // sets the width in pixels of the window.
			windowName:null, // name of window set from the name attribute of the element that invokes the click
			windowURL:null, // url used for the popup
			top:0, // top position when the window appears.
			toolbar:0 // determines whether a toolbar (includes the forward and back buttons) is displayed {1 (YES) or 0 (NO)}.
		};

		settings = $.extend({}, $.fn.popupWindow.defaultSettings, instanceSettings || {});

		var windowFeatures =    'height=' + settings.height +
								',width=' + settings.width +
								',toolbar=' + settings.toolbar +
								',scrollbars=' + settings.scrollbars +
								',status=' + settings.status +
								',resizable=' + settings.resizable +
								',location=' + settings.location +
								',menuBar=' + settings.menubar;

				settings.windowName = this.name || settings.windowName;
				settings.windowURL = this.href || settings.windowURL;
				var centeredY,centeredX;

				if(settings.centerBrowser){

					if ($.browser.msie) {//hacked together for IE browsers
						centeredY = (window.screenTop - 120) + ((((document.documentElement.clientHeight + 120)/2) - (settings.height/2)));
						centeredX = window.screenLeft + ((((document.body.offsetWidth + 20)/2) - (settings.width/2)));
					}else{
						centeredY = window.screenY + (((window.outerHeight/2) - (settings.height/2)));
						centeredX = window.screenX + (((window.outerWidth/2) - (settings.width/2)));
					}
					window.open(settings.windowURL, settings.windowName, windowFeatures+',left=' + centeredX +',top=' + centeredY).focus();
				}else if(settings.centerScreen){
					centeredY = (screen.height - settings.height)/2;
					centeredX = (screen.width - settings.width)/2;
					window.open(settings.windowURL, settings.windowName, windowFeatures+',left=' + centeredX +',top=' + centeredY).focus();
				}else{
					window.open(settings.windowURL, settings.windowName, windowFeatures+',left=' + settings.left +',top=' + settings.top).focus();
				}
				return false;
			});

		});
	};
})(jQuery);

/**
 * Make all the div block that have tabs.
 * This function will make the list as tabs.
 * @param {Object} options
 */
$.fn.makeLinksTabs = function(options){
    $(this).each(function(){
        var div_id = $(this).attr('id');
        $('#' + div_id + ' > ul').tabs("#" + div_id + " > .panes > div", {
            // just before tabs are clicked, we load the contents
            onClick: function(i){
                // get the pane to be opened
                var pane = this.getPanes().eq(i);
                // load contents only the first time it's opened
                if (pane.is(":empty")) {
                    pane.html("<div class='loading'><img src='/img/gears_animated.gif' width='16px' height='16px' /> Loading, Please Wait..</div>");
                    // transform anchor links to page URL'sthis.getTabs().eq(i).attr("href")
                    $.post(this.getTabs().eq(i).attr("href"), {
                        ajax_request: 1,
                        options: 2
                    }, function(data){
                        pane.html(data);
                    });
                }
            }
        })

    });
    return false;
};

/******************************************************/
/**
 * This function is called on dom load to make links ajaxified. this will cause the link to have ajax call and print the result in main div or the div_name specified
 * div_name > where you want to output the data. mainContent by default.
 * @param {Object} options
 */
$.fn.makeLinkAjaxified = function(options){
    this.bind('change click',function(){
//        var url = $(this).attr('link_id')?$(this).attr('link_id'):$(this).attr('href').replace(/\//g, "_");
        var url = $(this).attr('href').replace(/\//g, "."); //not using link_id any more.
        url = url.replace(/^.*#/, '');
        $.history.load(url);
        return false;
    });


};
/******************************************************/
/**
 * This function is called on dom load to make links ajaxified AND LOAD PARTIAL PAGES.
 * this will cause the link to have ajax call and LOAD PARTIAL PAGE BASED ON LAYOUT ID AND CHILD OFDIV
 * div_name > where you want to output the data. mainContent by default.
 * @param {Object} options.
 * NOT WORKING YET.DO NOT USE.
 */
$.fn.makeLinksPartialPageRequest = function(){
    this.click(function(){
        var div_name = ($(this).attr('div_name')) ? $(this).attr('div_name') : 'mainContent';
        $("#" + div_name).html("<div class='loading'><img src='/img/gears_animated.gif' width='16px' height='16px' /> Loading, Please Wait..</div>");
        $.post($(this).attr('href'), {
            partial_page_request: 1,
            layout_id: $(this).attr('layout_id'),
            child_of: $(this).attr('child_of')
        }, function(data){
            $("#" + div_name).html(data);
            initializeJqueryFunctions(div_name);
        });
        return false;
    });
}
/**
 * This functin is to make facebox load from ajax.
 * Facebox alread has this kind of functionality ut to make it compatible with the mvc framework or some reason I had to write this.
 * @param {Object} options
 */
/**this is not fully tested. think about havingajaixfied link inside facebox content?**/
$.fn.ajaxifiedFacebox = function(options){
    this.click(function(){
        //        $("#" + div_name).html("<img src='/img/gears_animated.gif' width='16px' height='16px' />Loading, Please Wait...");
        $.post($(this).attr('href'), {
            ajax_request: 1
        }, function(data){
            //            $("#" + div_name).html(data);
            jQuery.facebox(data);
        //  initFaceboxLinks(); i just need to init in the div..
        //  $("#" + div_name + ' a[rel*=facebox]').facebox(); //can I have a facebox popup inside a facebox? why would I?
        // $("#" + div_name + ' a[rel*=ajaxRequest]').makeLinkAjaxified();// and what about this?ok assume facebox is jst for information?
        // initAjaxRequestLinks();
        })
        return false;
    });


};
/**
 * This function is to make forms ajaxified.
 * Usage: rel='ajaxifiedForm'. required attributes > id , action . crate a blank div with id <id>_form_result. This is where the form result will be displayed.
 * Required: jquery Form and jquery validate
 *
 */
$.fn.makeFormAjaxified = function(options){
    this.each(function(){
        var formId = $(this).attr('id');
        var options = $.extend({
            submitHandler: function(form){
                $("#" + formId +'_form_result').html("<div class='loading'><img src='/img/gears_animated.gif' width='16px' height='16px' /> Loading, Please Wait..</div>");
                $('#' + formId + ' textarea[rel*=htmlTextEditor]').each(function(){
                    updateTextEditor($(this).attr('id'));
                });
                jQuery(form).ajaxSubmit({
                    target: "#" + formId + '_form_result',
                    data: ({
                        'ajax_request': 1 //You know this!!
                    }),
                    success:function(){
//                        setTimeout(function(){
//                            $('.close').click()
//                        },1000);
                    },
                    complete:function(){
                        initializeJqueryFunctions( formId + '_form_result')
                    }
                });
                if(!($('#'+formId).attr('keep_visible'))){
                    $('#' + formId).hide();
                }
                //Clear the output
                if (!($('#'+formId).attr('keep_result'))) {
                    setTimeout(function(){
                        $('#'+formId+'_form_result').html('')
                        },3000);
                }
            }
        }, options);
        var v = jQuery('#' + formId).validate(options);
    })
    return false;
};

$.fn.makeFormJsonAjaxified = function(options){
    this.each(function(){
        var formId = $(this).attr('id');
        var formTarget = "#" + formId + '_form_result';
        //Let's see if I have any wyzz area to be updated..
        //updateTextArea('body');
        var v = jQuery('#' + formId).validate({
            errorPlacement: function(error, element) {
                error.appendTo(element.prev('p'));
            },
            submitHandler: function(form){
                $("#" + formId +'_form_result').html("<div class='loading'><img src='/img/gears_animated.gif' width='16px' height='16px' /> Loading, Please Wait..</div>");
                $('#' + formId + ' textarea[rel*=htmlTextEditor]').each(function(){
                    updateTextEditor($(this).attr('id'));
                });
                jQuery(form).ajaxSubmit({
                    data: ({
                        'ajax_request': 1 //You know this!!
                    }),
                    dataType: 'json',
                    success:function(json) {
                        if(json.html) {
                            decodedHTML = decHTML(json.html);
                            $(formTarget).html(decodedHTML);
                        }
                        if (json.js) eval(json.js);
//                        if(json.close && json.close == true) {
//                            setTimeout(function(){$('.close').click()},1000);
//                        }
                    },
                    complete:function(){
                        initializeJqueryFunctions( formId + '_form_result')
                    }
                });
                //alert($('#'+formId).attr('keep_visible'));
                if(!($('#'+formId).attr('keep_visible'))){
                    $('#' + formId).hide();
                }
                //Clear the output
                if (!($('#'+formId).attr('keep_result'))) {
                    setTimeout(function(){
                        $('#'+formId+'_form_result').html('')
                        },3000);
                }
            }
        });
    //make jqueryfunctions if any for this new div..
    })
    return false;
};

//This simply decodes encoded HTML. Used for JSON responses containing HTML.
function decHTML(str){
    return str.replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>');
}

function imageSaved (conId, imageId, url) {
    org = $("input[name='id']").attr('org')
    div = '#image_v_' + org;
    $(div).attr('src', url);
	$(div + "_thumb").attr('src', url);
    if (org == '0') {
        $('#Image_' + imageId + "  input[name='id']").attr('value', imageId);
        $('#Image_' + imageId + "  input[name='content_image_id']").attr('value', conId);
    };
}
/**
 * make all the list show a varient of color.
 */
$.fn.makeAlternetColorList = function(options){
    //$(this).css("background-color",'#fff');
    //First get the current color//
    //alert($(this).css("background-color"));
    //var newColor = varientColor($(this).css("background-color"));
    //$(this).css("background-color",newColor);
    //$("div:even").css("background-color", "#EFF1F1");
    //For now..

    };
/*
 *Popup box
 */
$.fn.popUpBox = function(options){
    this.click(function(){
        var div_name = ($(this).attr('div_name')) ? $(this).attr('div_name') : 'popUpTempDivId';

        if(!($('#popUpTempDivId').length)){
            $('#mainContent').prepend("<div id='popUpTempDivId_overlay' class='globalOverlay'><div id='popUpTempDivId'></div></div>");
        }

        if(!($('#' + div_name + '_overlay').length)) {
            $('#mainContent').prepend("<div id='" + div_name + "_overlay' class='globalOverlay'><div id='" + div_name + "'></div></div>");
        }

        $("#" + div_name).html("<div class='loading'><img src='/img/gears_animated.gif' width='16px' height='16px' /> Loading, Please Wait..</div>");
        var onCloseFunction = ($(this).attr('oncloseFunction')) ? $(this).attr('oncloseFunction') : '';
        var test = $('#'+div_name+'_overlay').overlay({
            api:true
        });
        test.load();
        test.onClose(function(){
            eval(onCloseFunction);
            $('#'+div_name+'_overlay').remove();
            });
        var href = $(this).attr('href');
        if(href.indexOf('#', 0)){ //if it starts with # sign, it's a div. just get html from that div'
            $.post($(this).attr('href'), {
                ajax_request: 1
            }, function(data){
                $("#" + div_name).html(data);
                initializeJqueryFunctions(div_name);

            })
        }else{
            $("#" + div_name).html($(href).html());
        }
            
        return false;
    });
};

/**
 * set up jquery logging via the .log method
 */
jQuery.fn.log = function (msg) {
    console.log("%s: %o", msg, this);
    return this;
};

/**
 *run all the startup functions to make the links ajaxified and make tabs.
 */
function initializeJqueryFunctions(div_id){ //** Get some name for this function..
    var divId = (div_id == '') ? 'pageWrapper' : div_id; // pageWrapper is the main div whole site is wrapped in.
    //bind 	facebox links to facebox//
    $('#' + divId + ' a[rel=facebox]').facebox()

    //make ajaxified facebox//
    $('#' + divId + ' a[rel=ajaxifiedFacebox]').ajaxifiedFacebox()

    //make all links ajaxified those have ajaxRequest//
    //IE7 Fix for JQUERY
    $('#' + divId + ' a[rel=ajaxRequest]').each(function(){
        var cleanURL = $(this).attr('href');
        cleanURL = cleanURL.replace('http://'+window.location.host,'');
        $(this).attr('href',cleanURL);
    });
    //IE7 FIX ENDS//
    $('#' + divId + ' a[rel=ajaxRequest]').makeLinkAjaxified();

    //make all links ajaxified those have ajaxRequest//
    $('#' + divId + ' a[rel=partialPageRequest]').makeLinksPartialPageRequest();

    //make all links ajaxified those have ajaxRequest//
    $('#' + divId + ' a[rel=popUpBox]').popUpBox();

    //make all forms ajaxified //
    $('#' + divId + ' form[rel=ajaxifiedForm]').makeFormAjaxified();

    //make all forms ajaxified with Json response //
    $('#' + divId + ' form[rel=ajaxifiedFormJson]').makeFormJsonAjaxified();

    //make tabs//
    $('#' + divId + ' div[rel=makeItTab]').makeLinksTabs();

    $('#' + divId + ' [rel=alternateColorList]').makeAlternetColorList();
    //Make any input text box as date picker
    $('#' + divId + ' .datePicker').makeDatePicker();

	// make anchors work
	// rewrite <a rel="anchor"> tags
	$('#' + divId + ' a[rel="anchor"]').makeAnchorsScrollToId();
	// add id's to <a name> tags
	$('#' + divId + ' a[name]').addIdsToNames();
}

/**
 * Step 1 of making anchor # tags work on pages
 * a tags need to use the rel="anchor" for this to work
 */
$.fn.makeAnchorsScrollToId = function(options) {
	this.click(function(e) {$('html,body').animate({scrollTop: $($(this).attr('href')).offset().top - 10}, 500);return false;} );
}

/**
 * Step 2 of making the anchor tags work, this copies the name attribute into the id of the element
 */
$.fn.addIdsToNames = function(options) {
	this.attr("id", function() {return this.name;});
}

function varientColor(rgbString){

    var parts = rgbString.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
    // parts now should be ["rgb(0, 70, 255", "0", "70", "255"]

    delete (parts[0]);
    for (var i = 1; i <= 3; ++i) {
        parts[i] = parseInt(parts[i])+25;
    }
    //var newColor = parts.join(',');
    var newColor = 'rgb('+parts[1]+','+parts[2]+','+parts[3]+')';
    alert(newColor);
    return newColor;

}

//NEW DROPDOWN MENU CODE
var timeout = 20;
var closetimer = 0;
var ddmenuitem = 0;

function jsddm_open(){
    jsddm_canceltimer();
    jsddm_close();
    ddmenuitem = $(this).find('ul').css('visibility', 'visible');
}

function jsddm_close(){
    if (ddmenuitem)
        ddmenuitem.css('visibility', 'hidden');
}

function jsddm_timer(){
    closetimer = window.setTimeout(jsddm_close, timeout);
}

function jsddm_canceltimer(){
    if (closetimer) {
        window.clearTimeout(closetimer);
        closetimer = null;
    }
}

document.onclick = jsddm_close;
//yet another menu//
function mainmenu(){
    $(" #nav ul ").css({
        display: "none"
    }); // Opera Fix
    $(" #nav li").hover(function(){
        $(this).find('ul:first').css({
            visibility: "visible",
            display: "none"
        }).show(400);
    }, function(){
        $(this).find('ul:first').css({
            visibility: "hidden"
        });
    });
}



$(document).ready(function(){
initializeJqueryFunctions('');
    mainmenu();
});
//this function should be in something like adminsgeneral utils. js
function togglePublish(tableclass, rowId, div_id){
    var published = ($('#' + div_id).parent().hasClass('published')) ? '-' : 1;
    $.post('/admins/togglepublish/' + tableclass + '/' + rowId + '/', {
        'published': published,
        'id': rowId,
        ajax_request: 1
    }, function(data){
        //$('#' + div_id).attr('class',(($('#' + div_id).attr('class')=='icon published')?'icon unpublished':'icon published'));
        $('#' + div_id).parent().hasClass('published')?$('#' + div_id).parent().attr('class','icon unpublished'):$('#' + div_id).parent().attr('class','icon published');

    });
    return false;

}
function publishApproved(tableclass,rowId,div_id){
    var publish = ($('#' + div_id).parent().hasClass('publish')) ? '-' : 1;
   // alert($('#publish_'+rowId).attr('status_id'));
    if($('#publish_'+rowId).attr('status_id')==3)
    {
       $.post('/admins/publishApproved/' + tableclass + '/' + rowId + '/', {


         'published': publish,
         'status':'4',
         'id': rowId,
          ajax_request: 1

    }, function(data){
        $('#publish_'+rowId).attr('status_id', '4' )
        //$('#' + div_id).attr('class',(($('#' + div_id).attr('class')=='icon published')?'icon unpublished':'icon published'));
              $('#' + div_id).parent().hasClass('publish')?$('#' + div_id).parent().attr('class','icon unpublish'):$('#' + div_id).parent().attr('class','icon publish');

    });
    }
    else
    {
    $.post('/admins/publishApproved/' + tableclass + '/' + rowId + '/', {
        
     
         'published': publish,
         'status':'3',
         'id': rowId,
          ajax_request: 1

    }, function(data){
        $('#publish_'+rowId).attr('status_id', '3' )
        //$('#' + div_id).attr('class',(($('#' + div_id).attr('class')=='icon published')?'icon unpublished':'icon published'));
              $('#' + div_id).parent().hasClass('publish')?$('#' + div_id).parent().attr('class','icon unpublish'):$('#' + div_id).parent().attr('class','icon publish');

    });
    }
    return false;

}

function toggleApproved(tableclass,rowId,divId){
	if($('#'+divId).attr('status_id')==3) {
		$.post('/admins/toggleApprove/' + tableclass + '/' + rowId + '/', {
			'status':'4',
                        'published':'0',
			'id': rowId,
			ajax_request: 1
		}, function(data){
			$('#'+divId).attr('status_id', '4' )
			$('#' + divId).parent().hasClass('publish') ? $('#' + divId).parent().attr('class','icon unpublish') : $('#' + divId).parent().attr('class','icon publish');
		});
	} else {
		$.post('/admins/toggleApprove/' + tableclass + '/' + rowId + '/', {
			'status':'3',
			'id': rowId,
                        'published':'1',
			ajax_request: 1
		}, function(data){
			$('#'+divId).attr('status_id', '3' )
			$('#'+divId).parent().hasClass('publish') ? $('#' + divId).parent().attr('class','icon unpublish') : $('#' + divId).parent().attr('class','icon publish');
		});
	}
	return false;
}


function activate(content_id){
//if status is approved , do nothing
// if status is draft // call this method and make the status approval_pending//
// if status is approval_pending , alert that "this status is already pending for approval, you will receive an email once the content is approved."

  if(!checkActivated(content_id, true))
  {
      var div_id = 'pub_'+content_id;
    $.post('/contents/activate/' + content_id + '/', {
        'status': '4',
        'id': content_id,
        ajax_request: 1
    }, function(data){

        $('#pub_'+content_id).attr('status_id', '4' )
        $('#'+div_id).text('Approval Pending');
    });

  }
 
    return false;
}

function checkActivated(content_id, useAlert) {
    status_id = parseInt($('#pub_'+content_id).attr('status_id'));
    active = true;

    switch(status_id) {
        case 4:
            if (useAlert) alert('This content is already pending approval, you will receive an email once the content is approved.');
            break;
        case 3:
            if (useAlert) alert('This content is already approved.');
            break;
        case 1:
            active = false;
            break;
        case 0:
            active = false;
            break;
        default:
            alert("Error");
    }

    return active;
}

function savePublish (contentId, formName) {
    if (!checkActivated(contentId, false)) {
        $('#submit').val('true');
    }
    
    $(formName).submit();
}



//this function is not good. i need more complicated//
/**
 * I am using this function for taxonomy and ...
 * Delete a row from table provided and hides the div.
 * It actually sets a time out function so also provides some time to UNDO the action.
 * @param {Object} tableclass
 * @param {Object} rowId
 * @param {Object} div_id
 */
function deleteRow(tableclass, rowId, div_id, resourceId){
    resource = resourceId?resourceId:'';
    var msg = ($('#'+div_id+'_delete').attr('confirm_message')) ? ($('#'+div_id+'_delete').attr('confirm_message')): 'Are you sure to delete.\nThis will delete this content';
    if (confirm(msg)) {
        var deleteTimer = setTimeout(function(){
            $.post('/admins/deleteRow/' + tableclass + '/' + rowId + '/' + resource + '/', {
                'id': rowId,
                ajax_request: 1
            }, function(data){
                if(data.indexOf('Delete Success') !== -1){
                    $('#' + div_id).hide();
                }
                else{
                    $('#'+div_id).prepend("<div id='"+div_id+"_message' class='resultDiv' ></div>");
                    flashMessage({'messageDivName':div_id+'_message','message':data,'timeOut':4000});
                }
                $('#delete_undo_'+div_id).remove();
            });
        }, 3000);
//      $('#'+div_id).append("<div id='delete_undo_"+ div_id+"'><a href='javascript:void(0)' onclick=\"stopDelete("+deleteTimer+",'"+div_id+"');\">Undo</a></div>");
	$('#'+div_id).append("<a class='iconUndo' id='delete_undo_"+ div_id+"' href='javascript:void(0)' onclick=\"stopDelete("+deleteTimer+",'"+div_id+"');\">Undo</a>");
    }
    return false;
}
/**
 * To stop the delete action processed. This can actually be generic to stop any timeout function.
 * Used: deleteRow
 * @param {Object} deleteTimer
 * @param {Object} div_id
 */
function stopDelete(deleteTimer,div_id){
    clearTimeout(deleteTimer);
    $('#delete_undo_'+div_id).remove();
}

function urlencode(s){
    s = encodeURIComponent(s);
    return s.replace(/~/g, '%7E').replace(/%20/g, '+');
}
function makeTextEditor(textAreaId){
    var editorString = 'CKEDITOR.instances.'+textAreaId;
    var editor = eval(editorString);
    if(editor){

        CKEDITOR.remove(editor);
    }
    CKEDITOR.replace(textAreaId);
}

function makeUserTextEditor(textAreaId){
    var editorString = 'CKEDITOR.instances.'+textAreaId;
    var editor = eval(editorString);
    if(editor){

        CKEDITOR.remove(editor);
    }
    CKEDITOR.replace(textAreaId,
    {
         toolbar : 'User',
         height : '300',
         width : '90%'
    });
}

function updateTextEditor(textAreaId){
    //updateTextArea(textAreaId);
    var ckeditorInstanceString = 'CKEDITOR.instances.'+textAreaId;
    var ckEditor = eval(ckeditorInstanceString);
    $('#'+textAreaId).val(ckEditor.getData());
}

function insertIntoTextEditor(textAreaId,content) {
	var element = CKEDITOR.dom.element.createFromHtml( content );
	var ckeditor = eval("CKEDITOR.instances.body_"+textAreaId);
	ckeditor.insertElement( element );
}

function showEmail(prefix, suffix, display, href) {
    if (suffix == "") {
        suffix = "rodpub.com";
    }
    // setup mailto
    if (href == 1) {
        document.write("<a href='");
        document.write("mailto:");
        document.write(prefix + "@");
        document.write(suffix);
        document.write("'>");
    }
    // show mail or name
    if (display == "") {
        document.write(prefix + "@");
        document.write(suffix);
    } else {
        document.write(display);
    }
    // close mailto
    if (href == 1) {
        document.write("</a>");
    }
}

function showEmailIcon(prefix, suffix) {
    if (suffix == "") {
        suffix = "rodpub.com";
    }
    document.write("<a href='");
    document.write("mailto:");
    document.write(prefix + "@");
    document.write(suffix);
    document.write("'>");
    document.write("<img src='/img/icon_email.png' border='0'>")
    document.write("</a>");
}

function createInTextAd(keywords,adText) {
    $().ready(function(){
        keywordArray = keywords.split(",");
        for(var i in keywordArray) {
            var id = Math.floor(Math.random()*11111111);
            $('#mainContent').highlight(keywordArray[i], id);
            $("<div class='textAdBox' id='ad_"+id+"'><div class='textAdBoxContent'  ></div><img src='/img/icon_arrow_down.gif'></div>").appendTo("div#mainContent");
            $('#'+id).hover(function(){
                $('#ad_'+id+ '> .textAdBoxContent').html(adText);
            });
            $("#"+id).tooltip('#ad_'+id);
        }
    });
}
function reloadDiv(div_name,remoteUrl,loadText){
	if (loadText == undefined) loadText = "<img src='/img/gears_animated.gif' width='16px' height='16px' /> Loading, Please Wait..";
	else if (loadText == ' ') loadText = '';
    $("#" + div_name).html("<div class='loading'>"+loadText+"</div>");
    $.post(remoteUrl, {
        ajax_request: 1
    }, function(data){
        $("#" + div_name).html(data);
        initializeJqueryFunctions(div_name);
    });
}

/**
 * Get if cookie exists. 
 */
function getCookie(c_name)
{
if (document.cookie.length>0)
  {
  c_start=document.cookie.indexOf(c_name + "=");
  if (c_start!=-1)
    {
    c_start=c_start + c_name.length+1;
    c_end=document.cookie.indexOf(";",c_start);
    if (c_end==-1) c_end=document.cookie.length;
    return unescape(document.cookie.substring(c_start,c_end));
    }
  }
return false;
}
/**
 * Jquery function to flash messages on the fly. 
 * Utility class has an equivalent PHP function that calls this.
 * Usage: Utility::flashMessage(array('message'=>'','messageDivName'=>''));
 * message required. Divname options. it will flash it in mainContent. timeOut to time it out or it displays it forever.
 */

function flashMessage(settings){
    
    settings = $.extend({}, settings);
    //Let's find if we got a div name'
    var messageDivName =(settings.messageDivName)?settings.messageDivName:'defaultMessageDiv';
    var messageDiv = $('#'+messageDivName);
    //Create a default div if nothing found
    if(!messageDiv.length){
        $('#mainContent').prepend("<div id='"+messageDivName+"' class='messageDiv' ></div>");
            messageDiv = $('#'+messageDivName);
    }
    //Set the html
    messageDiv.html(settings.message?"<h2>"+settings.message+"</h2>":'');
    //Time out if requeste, or leave the message forever.
    if(settings.timeOut){
    setTimeout(function(){messageDiv.html('')},settings.timeOut);
    }

}
function popUpMessage(settings){
    settings = $.extend({},settings);
    $(document).mask('#000');
    $('#pageWrapper').prepend("<div id='popUpDivId_overlay' class='globalOverlay'><div id='popUpDivId'></div></div>");
    tempPopUpDiv = $('#popUpDivId_overlay');
    var onCloseFunction = (settings.onCloseFunction) ? settings.onCloseFunction : '';
    var popUpDiv = $('#popUpDivId_overlay').overlay({
        api:true
    });
    popUpDiv.load();
    if(settings.data){
        $('#popUpDivId').html(settings.data);
    }
    else if(settings.url){
        var postVar = $.extend({ajax_request:1},settings.postVar);
        $.post(settings.url, postVar, function(data){
            $('#popUpDivId').html(data);
            initializeJqueryFunctions('#popUpDivId');
        });
    }
    popUpDiv.onClose(function(){
        $.mask.close();
        eval(onCloseFunction);
    });
    return popUpDiv;

}
function getPartialPage(settings){
    settings = $.extend({},settings);
    var div_name = settings.div_name?settings.div_name:'mainContent';
    if(settings.data){
        $('#'+div_name).html(settings.data);
    }
    else if(settings.url){
        var postVar = $.extend({ajax_request:1},settings.postVar);
        $.post(settings.url, postVar, function(data){
            $('#'+div_name).html(data);
            initializeJqueryFunctions('#'+div_name);
        });
    }
}
 function togglePrimaryLink(link_id,content_id){
            if($('#primary_email_link_'+link_id).html() == 'Primary Email'){
                //link_id = 0;
            }
            reloadDiv('nowhere','/contents/setprimaryemail/'+link_id+'/'+content_id+'/');
            //set the styles//
            $('.primary_email_link').html('Set Primary Email');
            $('#primary_email_link_'+link_id).html('Primary Email');
    }
    //set the primary image text initially.

   
/**
 *
 * jquery.charcounter.js version 1.2
 * requires jQuery version 1.2 or higher
 * Copyright (c) 2007 Tom Deater (http://www.tomdeater.com)
 * Licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 */

(function($) {
	/**
	 * attaches a character counter to each textarea element in the jQuery object
	 * usage: $("#myTextArea").charCounter(max, settings);
	 */

	$.fn.charCounter = function (max, settings) {
		max = max || 100;
		settings = $.extend({
			container: "<span></span>",
			classname: "charcounter",
			format: "(%1 characters remaining)",
			pulse: true,
			delay: 0
		}, settings);
		var p, timeout;

		function count(el, container) {
			el = $(el);
			if (el.val().length > max) {
			    el.val(el.val().substring(0, max));
			    if (settings.pulse && !p) {
			    	pulse(container, true);
			    };
			};
			if (settings.delay > 0) {
				if (timeout) {
					window.clearTimeout(timeout);
				}
				timeout = window.setTimeout(function () {
					container.html(settings.format.replace(/%1/, (max - el.val().length)));
				}, settings.delay);
			} else {
				container.html(settings.format.replace(/%1/, (max - el.val().length)));
			}
		};

		function pulse(el, again) {
			if (p) {
				window.clearTimeout(p);
				p = null;
			};
			el.animate({opacity: 0.1}, 100, function () {
				$(this).animate({opacity: 1.0}, 100);
			});
			if (again) {
				p = window.setTimeout(function () {pulse(el)}, 200);
			};
		};

		return this.each(function () {
			var container;
			if (!settings.container.match(/^<.+>$/)) {
				// use existing element to hold counter message
				container = $(settings.container);
			} else {
				// append element to hold counter message (clean up old element first)
				$(this).next("." + settings.classname).remove();
				container = $(settings.container)
								.insertAfter(this)
								.addClass(settings.classname);
			}
			$(this)
				.unbind(".charCounter")
				.bind("keydown.charCounter", function () {count(this, container);})
				.bind("keypress.charCounter", function () {count(this, container);})
				.bind("keyup.charCounter", function () {count(this, container);})
				.bind("focus.charCounter", function () {count(this, container);})
				.bind("mouseover.charCounter", function () {count(this, container);})
				.bind("mouseout.charCounter", function () {count(this, container);})
				.bind("paste.charCounter", function () {
					var me = this;
					setTimeout(function () {count(me, container);}, 10);
				});
			if (this.addEventListener) {
				this.addEventListener('input', function () {count(this, container);}, false);
			};
			count(this, container);
		});
	};

})(jQuery);
/*
 * jQuery history plugin
 *
 * The MIT License
 *
 * Copyright (c) 2006-2009 Taku Sano (Mikage Sawatari)
 * Copyright (c) 2010 Takayuki Miwa
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

(function($) {
    var locationWrapper = {
        put: function(hash, win) {
            (win || window).location.hash = this.encoder(hash);
        },
        get: function(win) {
            var hash = ((win || window).location.hash).replace(/^#/, '');
            try {
                return $.browser.mozilla ? hash : decodeURIComponent(hash);
            }
            catch (error) {
                return hash;
            }
        },
        encoder: encodeURIComponent
    };

    var iframeWrapper = {
        id: "__jQuery_history",
        init: function() {
            var html = '<iframe id="'+ this.id +'" style="display:none" src="javascript:false;" />';
            $("body").prepend(html);
            return this;
        },
        _document: function() {
            return $("#"+ this.id)[0].contentWindow.document;
        },
        put: function(hash) {
            var doc = this._document();
            doc.open();
            doc.close();
            locationWrapper.put(hash, doc);
        },
        get: function() {
            return locationWrapper.get(this._document());
        }
    };

    function initObjects(options) {
        options = $.extend({
                unescape: false
            }, options || {});

        locationWrapper.encoder = encoder(options.unescape);

        function encoder(unescape_) {
            if(unescape_ === true) {
                return function(hash){return hash;};
            }
            if(typeof unescape_ == "string" &&
               (unescape_ = partialDecoder(unescape_.split("")))
               || typeof unescape_ == "function") {
                return function(hash) {return unescape_(encodeURIComponent(hash));};
            }
            return encodeURIComponent;
        }

        function partialDecoder(chars) {
            var re = new RegExp($.map(chars, encodeURIComponent).join("|"), "ig");
            return function(enc) {return enc.replace(re, decodeURIComponent);};
        }
    }

    var implementations = {};

    implementations.base = {
        callback: undefined,
        type: undefined,

        check: function() {},
        load:  function(hash) {},
        init:  function(callback, options) {
            initObjects(options);
            self.callback = callback;
            self._options = options;
            self._init();
        },

        _init: function() {},
        _options: {}
    };

    implementations.timer = {
        _appState: undefined,
        _init: function() {
            var current_hash = locationWrapper.get();
            self._appState = current_hash;
            self.callback(current_hash);
            setInterval(self.check, 10);
        },
        check: function() {
            var current_hash = locationWrapper.get();
            if(current_hash != self._appState) {
                self._appState = current_hash;
                self.callback(current_hash);
            }
        },
        load: function(hash) {
            if(hash != self._appState) {
                locationWrapper.put(hash);
                self._appState = hash;
                self.callback(hash);
            }
        }
    };

    implementations.iframeTimer = {
        _appState: undefined,
        _init: function() {
            var current_hash = locationWrapper.get();
            self._appState = current_hash;
            iframeWrapper.init().put(current_hash);
            self.callback(current_hash);
            setInterval(self.check, 10);
        },
        check: function() {
            var iframe_hash = iframeWrapper.get(),
                location_hash = locationWrapper.get();

            if (location_hash != iframe_hash) {
                if (location_hash == self._appState) {    // user used Back or Forward button
                    self._appState = iframe_hash;
                    locationWrapper.put(iframe_hash);
                    self.callback(iframe_hash);
                } else {                              // user loaded new bookmark
                    self._appState = location_hash;
                    iframeWrapper.put(location_hash);
                    self.callback(location_hash);
                }
            }
        },
        load: function(hash) {
            if(hash != self._appState) {
                locationWrapper.put(hash);
                iframeWrapper.put(hash);
                self._appState = hash;
                self.callback(hash);
            }
        }
    };

    implementations.hashchangeEvent = {
        _init: function() {
            self.callback(locationWrapper.get());
            $(window).bind('hashchange', self.check);
        },
        check: function() {
            self.callback(locationWrapper.get());
        },
        load: function(hash) {
            locationWrapper.put(hash);
        }
    };

    var self = $.extend({}, implementations.base);

    if($.browser.msie && ($.browser.version < 8 || document.documentMode < 8)) {
        self.type = 'iframeTimer';
    } else if("onhashchange" in window) {
        self.type = 'hashchangeEvent';
    } else {
        self.type = 'timer';
    }

    $.extend(self, implementations[self.type]);
    $.history = self;
})(jQuery);

jQuery(document).ready(function() {
    function load(url) {
		var logToGoogle = 1;
        var pageName = url;
        //        var ajaxLink = $("a[link_id="+url+"]"); //Not Using Link_id any more.
        //        var ajaxLinkURL = $(ajaxLink).attr('href');
        //        if(!ajaxLinkURL){
        var ajaxLink = $("a[href="+url.replace(/\./g, "/")+"]");
        var ajaxLinkURL = $(ajaxLink).attr('href');
        //        }
		if (pageName.substring(0,7) != 'comment') { // all disqus comments are #comment-123456789
			if(!(ajaxLinkURL)){ //so i still didn't get it. but i have a ajax request history page to load.'
				ajaxLinkURL = url.replace(/\./g, "/");
			}
			var div_name = ($(ajaxLink).attr('div_name')) ? $(ajaxLink).attr('div_name') : 'mainContent';
			$("#" + div_name).html("<div class='loading'><img src='/img/gears_animated.gif' width='16px' height='16px' /> Loading, Please Wait..</div>");
			if ($(ajaxLink).attr('no_scroll')) {
				$('html, body').animate({
					scrollTop:0
				}, 'slow');
			}
			var options = $(ajaxLink).attr('options');
			$.post(ajaxLinkURL, {
				ajax_request: 1,
				logToGoogle:logToGoogle,
				pageName:pageName,
				options: options
			}, function(data){
				$("#" + div_name).html(data);
				initializeJqueryFunctions(div_name);
			});
//		} else {
//			$("body").animate({scrollTop: $("#dsq-"+pageName).offset().top - 40},0);
		}
    }

	$.history.init(function(url) {
        if(url != ''){
            $().ready(function(){
                load(url);
            })
                    
        }
        return false;
    });

       
});
$.fn.makeDatePicker = function(options){
    $(this).datepicker({dateFormat: 'yy-mm-dd'});
}

function translateString(s) {
	if(!translateString.translate_re) translateString.translate_re = /[äöüÄÖÜáàâéèêúùûóòôÁÀÂÉÈÊÚÙÛÓÒÔß–—]/g;
	var translate = {
		"ä": "a", "ö": "o", "ü": "u",
		"Ä": "A", "Ö": "O", "Ü": "U",
		"á": "a", "à": "a", "â": "a",
		"é": "e", "è": "e", "ê": "e",
		"ú": "u", "ù": "u", "û": "u",
		"ó": "o", "ò": "o", "ô": "o",
		"Á": "A", "À": "A", "Â": "A",
		"É": "E", "È": "E", "Ê": "E",
		"Ú": "U", "Ù": "U", "Û": "U",
		"Ó": "O", "Ò": "O", "Ô": "O",
		"ß": "s", "—": "-", "–": "-"
	};
	return ( s.replace(translateString.translate_re, function(match) {
		return translate[match];
	}) );
}

function createSlug(elm_id, slug) {
	var slug = new String(slug);
	slug = translateString(slug);
	document.getElementById(elm_id).value = slug.substring(0,150).toLowerCase().trim().replace(/[^a-z0-9 -]/g,'').replace(/\s+|-+/g,'-');
}

$.validator.addClassRules({
    phone: {
        required: false
    }
});

$.validator.addMethod('phone', function (value) {
    var numbers = value.split(/\d/).length - 1;
    if (value.length == 0) return true;
    return (10 <= numbers && numbers <= 18 && value.match(/^((\+)?[1-9]{1,2})?([-\s\.])?((\(\d{1,4}\))|\d{1,4})(([-\s\.])?[0-9]{1,12}){1,2}(\s*(ext|x)\s*\.?:?\s*([0-9]+))?$/));
}, 'Please enter a valid phone number (Intl format accepted + ext or x)');

//First make a reference to the original validation method.
$.validator.methods.orgURLValidator = $.validator.methods.url;
$.validator.addMethod('url', function (value, element, param) {
    value = ((value.substring(0,7) == 'http://') || (value.substring(0,8) == 'https://')) ? value : 'http://' + value;
    return $.validator.methods.orgURLValidator.call(this, value, element, param);
}, $.validator.messages.url)

jQuery.fn.chainSelect = function( target, url, settings )
{
    return this.each( function()
    {
        $(this).change( function( )
        {
            settings = jQuery.extend(
            {
                after : null,
                before : null,
                usePost : false,
                defaultValue : null,
                parameters : {
                    '_id' : $(this).attr('id'),
                    '_name' : $(this).attr('name'),
                    'ajax_request' : 1
                    }
            } , settings);

            settings.parameters._value =  $(this).val();
            settings.parameters._alt = ($('#' + settings.parameters._id + " option:selected").attr('alt')) ? $('#' + settings.parameters._id + " option:selected").attr('alt') : '';


            if (settings.before != null)
            {
                settings.before( target );
            }

            ajaxCallback = function(data, textStatus)
            {
                $(target).html(""); //clear old options

                data = eval(data); //get json array

                if (data != null && !$.isEmptyObject(data)) {

                    for (i = 0; i < data.length; i++)//iterate over all options
                    {
                        alt = (settings.map.alt) ? 'alt = "' + data[i][settings.map.alt] + '"' : '';
                        value = (settings.map.value) ? 'value = "' + data[i][settings.map.value] + '"' : '';
                        name = (settings.map.name) ? data[i][settings.map.name] : '';

                        option = '<option ' + alt + ' ' + value + '>' + name + '</option>';
                        $(target).append(option);
                    }

                    if (settings.defaultValue != null)
                    {
                        $(target).val(settings.defaultValue);//select default value
                    } else {
                        $("option:first", target).attr( "selected", "selected" );//select first option
                    }

                }
                else {
                        option = '<option ' + ' value="0">There are no sub-regions for this country.</option>';
                        $(target).append(option);
                }

                if (settings.after != null)
                {
                    settings.after(target);
                }

                $(target).change();//call next chain
            };

            $.post( url, settings.parameters, ajaxCallback );

        });
    });
};
