/* ----------- JQuery substitute for lack of CSS --------------*/
$(document).ready(function() {
	/*
    $('.new_form input[@type=text]').css({
        'width': '300px'
    });
    $('.new_form textarea').css({
        'width': '300px'
    });
    */
});


/* ----------- START of AJAX functions(moved from ajax.js) --------------*/

// Calls success_handler() if src_url loaded successfully.
// Otherwise error_handler() if specified
function ajaxRequest( src_url, success_handler, error_handler ){
    if((!src_url) || (!success_handler))
        return false;

    $.ajax({
        type: "GET",
        url: src_url,
        dataType: "html",
        data: "javascript=true",
        success: success_handler,
        error: error_handler
    });

    return false;
}

//Submits the form with specified id using its 'method' and 'action' properties.
// submission url could be replaced with custom_url
// if form is submitted successfully, success_handler() will be called,
// on error - error_handler()
// If request returned the XML content and success_handler is not specified,
// the default XML parsed would be called (ajaxDefaultXMLParser)
function ajaxSubmitForm( form_id, custom_url, success_handler, error_handler ){
	var form = $("#"+form_id);
	var url = '';
	var method = 'GET';

	if ( !form.is("form") )	return false;

	if( !custom_url ) {
		if( form.attr("action") != undefined )
			url = form.attr("action");
	}else{
		url = custom_url;
	}

	if( url == '' || url == undefined )	return false;

	if( form.attr("method") != undefined )
		method = form.attr("method");

	var params = ajaxComposeParams( form_id )+'&ajax_submit=true';


	$.ajax({
        type: method,
        url: url,
        dataType: "script",
        data: params,
        success: success_handler,
        error: error_handler,
        complete: function(){enableControls( form_id );}
    });

    disableControls( form_id );

    return true;
}

function error_handler( request, error_string, exception )
{
    alert(request.status + "    " + request.statusText);
}

// explicitly replaces the content of specified HTML element with result of requesting src_url
function ajaxSetContent( element_id, src_url ){
	var callback = function(response_data){fillContent( element_id, response_data );};
	return ajaxRequest( src_url, callback, error_handler );
}

// eSimilar to ajaxSetContent, but replaces form field value
function ajaxSetValue( element_id, src_url ){
	var callback = function(response_data){fillValue( element_id, response_data );};
	return ajaxRequest( src_url, callback );
}


// represents form params as a string
// supports text, textarea, radiobuttons, select (not multiple), checkboxes..
function ajaxComposeParams( form_id ){
	return $('#'+form_id).formSerialize();
}

// disables all elements of form
function disableControls( form_id ){
    $('#'+form_id+' :input').attr("disabled", true);
}

// enables all form elements
function enableControls( form_id ){
	$('#'+form_id+' :input').attr("disabled", false);
}

// sets the innerHTML property of specified element
function fillContent( elem_id, new_val ){
    if ( new_val.substr(0,6) == 'LOGOUT' ){
	   $('body').html(new_val.substr(6));
    }else{
	   $('#'+elem_id).html(new_val);
    }
}

// sets the value property of form elemenet
function fillValue( elem_id, new_val){
    $('#'+elem_id).val(new_val);
}

function spinner_on(spiner_id, timeout){
    /* This function starts a spinning wheel */
    var spinner = $('#'+spiner_id);
    if( spinner.is('img') ){
        spinner.attr('src', 'templates/kt2/images/loading.gif');
    }else{
        spinner.html('<img src="templates/kt2/images/loading.gif" alt="loading">');
    }

    if( timeout == null ) timeout = 3000;
    if( timeout > 0 ) setTimeout("spinner_off('"+spiner_id+"')",timeout);
}
function spinner_off(spiner_id){
    /* This function stops a spinning wheel */
    var spinner = $('#'+spiner_id);
    if( spinner.is('img') ){
        spinner.attr('src', 'templates/kt2/images/not_loading.gif');
    }else{
        spinner.html('<img src="templates/kt2/images/not_loading.gif" alt="loading">');
    }
}

function setVisibility(element,visible){
    if(visible){
        $('#'+element).show();
    }else{
        $('#'+element).hide();
    }
}
function setOverlayVisibility(element,visible){
    if(visible){
        var JQElement = $('#RD_'+element).parent();
        iframe=$('<iframe class="jqm"></iframe>').css({'opacity':0,'wdith':'100%','height':'100%'});
        $('#RD_'+element).css({
            'height': JQElement.height(),
            'width': JQElement.width(),
            'left': JQElement.offset().left,
            'top': JQElement.offset().top,
            'background-color': '#000000',
            'opacity': 0.2,
            'z-index': 30
        });
        $('#RD_'+element).prepend(iframe);
        $('#RI_'+element).css({
            'left': JQElement.offset().left + JQElement.width()/2 - 50,
            'top': JQElement.offset().top + JQElement.height()/2 - 50,
            'z-index': 40
        });
        $('#RD_'+element).show();
        $('#RI_'+element).show();
    }else{
        $('#RI_'+element).hide();
        $('#RD_'+element).hide();
    }
}


function resetForm(form){
    $('#'+form).resetForm();
}

function setFieldValue(form,field,value){
    $('#'+form+' [@name='+form+'_'+field+']').val(value);
}

function setFormFocus(form,field){
	$('#'+form+' [@name='+form+'_'+field+']').focus();
}


function submitForm(form,spinner){
	var callback = function(response_text, response_xml){
        if(spinner)spinner_off(spinner);
    }
    return ajaxSubmitForm(form,null,callback);
}



/* ----------- END of AJAX functions(moved from ajax.js) --------------*/


//KeyCodes
var kReturn=13;
var kTab=9;
var kEsc=27;


var open_expanders=new Array();
    /* we remember opened expanders so we know what to do when clicked */
var inline_active=new Array();
    /* same as for expanders, but applying to inline edits.
       they should be processed differently
       this array contains URLs to close inlines
    */
function inline_is_active(name, id)
{
	if( inline_active[name] )
	   return inline_active[name][id];
	else
	   return false;
}

/******* Expander functions ********/

function getExpanderStatus(name, id, button)
{
    /*
     * This would just return exander's state on a button click. If another expander is
     * open, it would not do anything, just return it's button's name.
     */
    //inlines should be hidden anyway
    if( inline_is_active(name,id) ) return "inline_active";

    if( open_expanders[name+"_"+id] == button )
    {
        return "is_open";
    }
    else if( open_expanders[name+"_"+id] )
    {
        return open_expanders[name+"_"+id];
    }
    else
    {
        return "is_closed";
    }
}

function expanderOn(id)
{
    var button = $('#'+id);

    button.siblings().removeClass('expanded_this');
    button.siblings().removeClass('not_expanded');
    button.removeClass('not_expanded');
    button.siblings().addClass('expanded_other');
    button.addClass('expanded_this');
}

function expanderOff(id)
{
    var button = $('#'+id);

    button.removeClass('expanded_this');
    button.siblings().removeClass('expanded_other');
    button.parent().children().addClass('not_expanded');
}

function expanderAnimate(id)
{
    $('#'+id).animate({height:200}, 450);
}

function expanderFlip(name,id,button,expander_url)
{
    /*
     * This opens/closes lister's expander. Use this function
     * under 'onclick' for your table row. It will take care of
     * adding additional row and loading content there. expander_url is
     * a prefix, which will have id appended
     */

    var row    = $('#'+name+'_'+id);
    var status = getExpanderStatus(name, id, button);

    if( status == "is_open" )
    {
        open_expanders[name+'_'+id] = '';
        row.next().remove();
        expanderOff(name+"_"+button+"_"+id);
    }
    else if( status == "inline_active" )
    {
        inlineHide(name,id);
        expanderFlip(name,id,button,expander_url);
    }
    else if( status == "is_closed" )
    {
        open_expanders[name+'_'+id] = button;

        var newcell = row.after('<tr></tr>').next().append('<td></td>').children();

        newcell.css({
            'background-color': '#FFFFFF',
            'border-width': '0 1px 1px 1px',
            'border-color': '#4F5330',
            'border-style': 'solid',
            'padding': '15px'
        });
        newcell.attr('colSpan', row.children().length);
        newcell.attr('id', name+"_expandedcontent_"+id);
        newcell.html('<table cellspacing=0 cellpadding=0 border=0><tr><td valign=top><img src=templates/kt2/images/loading.gif></td><td>&nbsp;</td><td class="smalltext" align=center id="autoexpander_'+id+'" valign=top><b style="color:#779f18">Loading. Stand by...</b></td></tr></table>');


        ajaxSetContent(name+"_expandedcontent_"+id, expander_url+id);

        expanderAnimate('autoexpander_'+id, 0);

        expanderOn(name+"_"+button+"_"+id);
    }
    else
    {
        /* If other expander is active, close that one and open new one */
        expanderFlip(name, id, status, expander_url);
        expanderFlip(name, id, button, expander_url);
    }

}
/******* InlineEdit functions ********/

function getInlineValue(inline_id)
{
	return $('#'+inline_id).attr('title');
}

function isKeyPressed(event, kCode)
{
	return event.which == kCode;
}

function denyEnter(e)
{
	return !isKeyPressed(e, kReturn);
}

function processInlineKey(event)
{
    var name = event.data.name;
    var id   = event.data.id;
    var activate_next = event.data.activate_next;

	if( isKeyPressed(event, kEsc) )
	{
	    //hide current inline
		inlineHide(name, id, 'cancel');
		return false;
	}
	if( isKeyPressed(event, kReturn) )
	{
		//submit and hide current inline
		inlineHide(name, id, 'update');
		return false;
	}

	return true;
}

function inlineShow(name, active_field, row_id, submit_url, activate_next, show_submit, on_submit_fun, on_cancel_fun)
{
	/*
	 * Changes row content to a forms with input elements
	 * Params:
	 *     - submit_url - URL used in ajax request to store inline values
	 *     - name - name of the grid
	 *     - active_field - name of inline element that was clicked (that should be made active)
	 *     - row_id - the row id
	 *     - on_submit_fun and on_cancel_fun - callbacks for OK and Cancel buttons
    */
	var inline_id = active_field + "_" + row_id;

	//close all open expanders
	var expander_id = name + "_" + row_id;
	if( open_expanders[expander_id] )
	{
		expanderFlip(name, row_id, open_expanders[expander_id]);
	}
	//close all active inlines
	if( inline_active[name] )
	{
		for( i = 0; i < inline_active[name].length; i++ )
			if( inline_active[name][i] ) inlineHide(name,i);
	}

	var expander_row = $('#'+expander_id);

	//change row contents to the forms, for all inlines
	var inline_collection = new Array();
	var index = 0;


	expander_row.children().each( function()
	{
        id = new String($(this).attr('id'));

        if( id.indexOf('_inline') != -1 )
        {
			var form_name = 'form_' + id;

			// setting input size to length of the text in it or 40 max
			value = getInlineValue(id);
			size = value.length < 3 ? 3 : ( value.length > 40 ? 40 : value.length );

			$(this).html('<form class="inlide_edit_form" id="' + form_name + '" name="' + form_name + '" method="POST">'+
			             '<input id="' + form_name + '_edit" value="'+
			             value+'" size="'+size+'" type="text"></form>');

			$('#'+form_name+'_edit').bind('keypress', { 'name': name, 'id': row_id, 'activate_next': activate_next  }, processInlineKey);

			inline_collection[index] = form_name;
			index++;
		}
	});

	if( show_submit )
	{
		//expanding a row with submits
		newcell = expander_row.after('<tr></tr>').next().append('<td></td>').children();

        newcell.css({
            'background-color': '#FFFFFF',
            'border-width': '0 1px 1px 1px',
            'border-color': '#000',
            'border-style': 'solid',
            'padding': '1px'
        });
        newcell.attr('colSpan', expander_row.children().length);
        newcell.attr('align', 'right');

        if( typeof(on_submit_fun) == 'undefined' ) on_submit_fun = '';
		else on_submit_fun = ',\'' + on_submit_fun + '(\\\'' + name + '\\\',\\\'' + row_id + '\\\')\'';

		if( typeof(on_cancel_fun) == 'undefined' ) on_cancel_fun = '';
		else on_cancel_fun = ',\'' + on_cancel_fun + '(\\\'' + name + '\\\',\\\'' + row_id + '\\\')\'';

		event_handler = "inlineHide('" + name + "'," + row_id + ",'";

		newcell.html('<div style="padding:3px;">' +
		             '<form method="POST">' +
        			 '<button class="button" type="button" name="OK" value="OK" onclick="' + event_handler + 'update\'' + on_submit_fun + ');"><span>OK</span></button>&nbsp;&nbsp;' +
        			 '<button class="button" type="button" name="Cancel" value="Cancel" onclick="' + event_handler+'cancel\'' + on_cancel_fun + ');"><span>Cancel</span></button>' +
        			 '</form></div>');


	}

	//setting an array value for further hiding
	if( !inline_active[name] ) inline_active[name] = new Array();

	inline_active[name][row_id] = new Array();
	inline_active[name][row_id]['submit_url'] = submit_url;
	inline_active[name][row_id]['inline_collection'] = inline_collection;
	inline_active[name][row_id]['active_field'] = active_field;
	inline_active[name]['show_submit'] = show_submit;
}

function inlineHide(name, row_id, action, callback)
{
	//name is a grid name, id is a row id
	//processing inline: submit or cancel
	//callback - callback function with params
	var submit_url = inline_active[name][row_id]['submit_url'] + '&row_id=' + row_id;
	var inline_collection = inline_active[name][row_id]['inline_collection'];

	if( action )
		var url = submit_url + '&action=' + action;
	else
		var url = submit_url + '&action=update';

	var reload_row = false;
	if( inline_collection )
	{
		var url_params = "";
		for( i = 0; i < inline_collection.length; i++ )
		{
			field_name = new String(inline_collection[i]);
			field_name = field_name.substring(name.length + 6, field_name.indexOf('_inline'));
			field = $('#' + inline_collection[i] + ' input[@type=text]');
			if( field.is('input') )
			{
				url_params += '&' + 'field_' + field_name + '=' + encodeURIComponent(field.val());
				reload_row = true;
			}
		}
		url = url + url_params;
	}
	if( reload_row )
	{
		reloadGridRow(url, name, row_id, callback);
		if( inline_active[name]['show_submit'] )
		{
			//hide buttons
			$('#' + name + '_' + row_id).next().remove();
		}
	}
	inline_active[name][row_id] = false;
}

/**
 * Reloads a row of a Grid
 */
function reloadGridRow(url, name, row_id, callback){
	//row contents could not be replaced with ajaxSetContent
	set_row_c = function(response_text, response_xml)
	{
		//exploding string to an array of column values
		cols = response_text.split('<row_end>');

		$('#' + name + '_' + row_id).children().each( function(i)
		{
            if( $(this).html() != undefined )
            {
                value = cols[i].split('<t>');
                $(this).html(value[0]);
                $(this).attr('title', value[1]);
            }
		});

		try
		{
			if( typeof(callback) != 'undefined') eval(callback);
		} catch(e) {}
	}
	ajaxRequest(url, set_row_c);
}

/******* TreeView functions *******/

function treenode_flip(expand, id, url, zone)
{
	button = new String($('#' + 'ec_' + id + zone).html());

	if( expand == 1 )
	   $('#' + 'p_' + id + zone).html('<table cellspacing=0 cellpadding=0 border=0><tr><td valign=top><img src=templates/kt2/images/loading.gif></td><td>&nbsp;</td><td class="smalltext" align=center id="autoexpander_'+id+'" valign=top><b style="color:#779f18">Loading. Stand by...</b></td></tr></table>');

	ajaxSetContent('p_' + id + zone,url);

	if( expand == 1 )
	{
		button = button.replace('plus.gif', 'minus.gif');
		button = button.replace('ec_action=expand', 'ec_action=collapse');
		button = button.replace('treenode_flip(1', 'treenode_flip(0');
	}
	else
	{
		button = button.replace('minus.gif', 'plus.gif');
		button = button.replace('ec_action=collapse', 'ec_action=expand');
		button = button.replace('treenode_flip(0', 'treenode_flip(1');
	}
	$('#' + 'ec_' + id + zone).html(button);
}

function righttreenode_flip(expand, id, url, id_select)
{
    button = new String($('#' + 'ec_' + id).html());

	if( expand == 0 )
	   $('#' + 'p_' + id).html('<table cellspacing=0 cellpadding=0 border=0><tr><td valign=top><img src=templates/kt2/images/loading.gif></td><td>&nbsp;</td><td class="smalltext" align=center id="autoexpander_'+id+'" valign=top><b>Loading. Stand by...</b></td></tr></table>');

	ajaxSetContent('p_' + id,url);

	if( expand == 1 )
	{
	    button = button.replace('minus.gif', 'plus.gif');
		button = button.replace('ec_action=collapse', 'ec_action=expand');
		button = button.replace('treenode_flip(1', 'treenode_flip(0');
	}
	else
	{
		button = button.replace('plus.gif', 'minus.gif');
		button = button.replace('ec_action=expand', 'ec_action=collapse');
		button = button.replace('treenode_flip(0', 'treenode_flip(1');
	}
	$('#' + 'ec_' + id).html(button);
}

function set_rights(reset, template_id, obj)
{
    //loop forms to find the right one ... hidden and with the correct id
    $('form').each(function()
    {
        pieces = $(this).attr('id').split('_');
        if( pieces.length > 4 )
        {
            if (( pieces[pieces.length-1] == 'HiddenForm' && pieces[pieces.length-4] == template_id ) || (pieces[pieces.length-1] == 'AddAccessTemplateHiddenForm'))
            {
                //loop through form elements, and populate them with the relevant info (or reset them)
                $(this).find('input[@type=hidden]').each(function()
                {
                    name = $(this).attr('name');
					if( name.substr(name.length-6, 6) == 'rights' )
                    {
				        if( reset )
				            $(this).val('');
				        else
				            $(this).val( $(this).val() + $(obj).val() + "_" );

    				}
    				else if( name.substr(name.length-8, 8) == 'sections' )
    				{
    				    if( reset )
    				    {
                            $(this).val('');
    				    }
    				    else
    				    {
    				        arr = $(obj).attr('id').split('_');
    				        $(this).val( $(this).val() + arr[1] + "_" );
    				    }
    				}
                });
            }
        }
    });
}


/******* Jump To functions ********/

var jump_to_switches = new Array();

function jumpToOpen(id)
{
    jump_to_switches[id] = true;
    $('#'+id+'_trigger').hide();
    $('#'+id).SlideInUp('normal');
}
function jumpToClose()
{
    if( jump_to_switches[this.id] )
    {
        $('#'+this.id).SlideOutUp('normal',function(){$('#'+this.id+'_trigger').show();});
        jump_to_switches[this.id] = false;
    }
}


/******* Color Picker functions ********/

function getMouseX(evt) {
    if (evt.pageX) return evt.pageX;
    else if (evt.clientX)
        return evt.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
    else return null;
}

function getMouseY(evt) {
    if (evt.pageY) return evt.pageY;
    else if (evt.clientY)
       return evt.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
    else return null;
}

function togglePicker(event,element,callback,params)
{
    if( togglePicker.element == element )
    {
        $('#color_picker_container').hide();
        togglePicker.element = null;
    }
    else
    {
        if( togglePicker.container == undefined )
        {
            //alert(params);
            $('#color_picker_container').remove();
            togglePicker.element = element;

            togglePicker.container = $('<div id="color_picker_container" class="color_picker_container"></div>');
            togglePicker.container.css({
                'width': 195,
                'height': 195,
                'left': getMouseX(event)+2,
                'top': getMouseY(event)+2,
                'z-index':30
            });

            togglePicker.close = $('<div class="color_picker_close" onclick="closePicker()"></div>').css({ 'left': 14, 'top': 14 });


            togglePicker.iframe = $('<iframe class="jqm" src=""></iframe>').css({ 'opacity':0, 'height': '100%', 'width': '100%' });

            togglePicker.picker = $('<div class="color_picker_arrow"></div>');

            togglePicker.container.prepend(togglePicker.picker);
            togglePicker.container.prepend(togglePicker.close);
            togglePicker.container.prepend(togglePicker.iframe);
            $('body').prepend(togglePicker.container);

            togglePicker.farbtastic = $.farbtastic(togglePicker.picker,callback,params);
        }
        else
        {
            //alert(params);
            togglePicker.element = element;

            togglePicker.container.css({
                'left': getMouseX(event)+2,
                'top': getMouseY(event)+2
            });
            togglePicker.farbtastic.linkTo(callback, params);
            togglePicker.container.show();
        }
    }

}

function closePicker(){
    $('#color_picker_container').hide();
    togglePicker.element = null;
}



/******* MISC FUNCTIONS *******/


function toggleSelectCountry(source, element)
{
    $('input[@name=' + source + ']').each(function()
    {
        if( $(this).attr('checked') == true )
        {
            if ( $(this).val() == 0 )
                setVisibility(element, false);
            else
                setVisibility(element, true);
        }
    });
}

function toggleTargetType(source, element)
{
    var target = $('#' + element).parent().parent();
    if( $('#' + source).val() == 0 )
        target.hide();
    else
        target.show();
}

function toggleLoginsOptions(sourceName, element)
{
	var source = document.getElementsByName(sourceName);
	for (var i = 0;i<source.length;i++){
		if (source[i].checked) value = source[i].value;
	}
	var publisherLoginInputs = document.getElementsByName('publisherLogin');

	if (value == 0) {
	    setVisibility(element,false);
		for (index=0; index < publisherLoginInputs.length; index++) {
		    publisherLoginInputs[index].style.display = 'block';
		}
	}
	else {
	    setVisibility(element,true);
		for (index=0; index < publisherLoginInputs.length; index++) {
		    publisherLoginInputs[index].style.display = 'none';
		}
	}
	//document.getElementById(element).focus();
}

function moveTransferrableItems(name, type){ //type => 'forward' || 'backward'

    if (type == 'forward'){
        source = $('#' + name + '_start:input');
        target = $('#' + name + '_end:input');
    } else {
        source = $('#' + name + '_end:input');
        target = $('#' + name + '_start:input');
    }

    selected_options = [];
    source_options = source[0].options;
    for (var i=0; i < source_options.length; i++){
            if (source_options[i].selected == true) {
                selected_options.push(source_options[i]);
        }
    }

    for (var j=0; j < selected_options.length;j++){
        source[0].options[selected_options[j].index] = null;
        target[0].options[target[0].options.length] = selected_options[j];
    }
}

// -- functions that work with offers widgets


function showHideMe(object,name,img_on,img_off){
    content = $(object).parents('.widget').children('.widget_content');
    content_list = content.children('ul');
    if ((typeof(content[0].status) == 'undefined') || (content[0].status == 'closed')){
        content[0].status = 'opened';
        document.cookie = name + '=opened';
        $(object).addClass('expanded');
        $(object).children().children().children().css('background-image','url(templates/kt2/images/'+img_on+')');
        content_list.show();
        content.slideDown();
    }else{
        content[0].status = 'closed';
        document.cookie = name + '=closed';
        content.slideUp(function(){ content_list.hide() });
        $(object).removeClass('expanded');
        $(object).children().children().children().css('background-image','url(templates/kt2/images/'+img_off+')');
    }
}

function showHideList(object,name,node){
    list = $(object).parent().children('ul');

    cookie = readCookie(name);
    nodes = cookie.substring(6,cookie.length);
    if (list.css('display') == 'none'){
        $(object).removeClass('expandable_widget_label');
        $(object).addClass('expanded_widget_label');
        list.slideDown();
        nodes = nodes + '|' + node;

    }else{
        $(object).removeClass('expanded_widget_label');
        $(object).addClass('expandable_widget_label');
        list.slideUp();
        nodes = nodes.replace('|' + node,'');
    }
    document.cookie = name + '=opened' + nodes;
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function showPayoutsHistory(obj){
    list = $('#payouts_history');
    if (list.css('display') == 'none')
    {
        list.slideDown();
        $(obj).html('Hide Payouts History');
    }
    else
    {
        list.slideUp();
        $(obj).html('Show Payouts History');
    }
}


function showCreativeCodes(obj){

    list = $('#creative_codes');
    if (list.css('display') == 'none')
    {
        list.slideDown();
        $(obj).html('Hide Creative Codes');
    }
    else
    {
        list.slideUp();
        $(obj).html('Show Creative Codes');
    }
}

function showCreativeImage(obj){

    list = $('#creative_image');
    if (list.css('display') == 'none')
    {
        list.slideDown();
        $(obj).html('Hide Creative Image');
    }
    else
    {
        list.slideUp();
        $(obj).html('Show Creative Image');
    }
}


function showExportMenu(obj){


    list = $('#export_menu');
    if (list.css('display') == 'none')
    {
        list.slideDown();
        $(obj).parent().removeClass("grid_toolbar_menu_link");
        $(obj).parent().addClass("grid_toolbar_menu_link_expanded");
    }
    else
    {
        list.slideUp();
        $(obj).parent().removeClass("grid_toolbar_menu_link_expanded");
        $(obj).parent().addClass("grid_toolbar_menu_link");
    }
}


function submitQuickSearch(obj){
    obj = $(obj);
    form = obj.parents('form');
    form.submit();
}

jQuery.fn.rating = function(options) {

    var settings = {
        maxvalue  : 10,   // max number of stars
        curvalue  : 0    // number of selected stars
    };

    if(options) {
       jQuery.extend(settings, options);
    };

    var stars = jQuery(this).children('.star');

    stars
        .mouseover(function(){
            event.drain();
            event.fill(this);
        })
        .mouseout(function(){
            event.drain();
            event.reset();
        })
        .focus(function(){
            event.drain();
            event.fill(this)
        })
        .blur(function(){
            event.drain();
            event.reset();
        });

    var event = {
		fill: function(el){ // fill to the current mouse position.
			var index = stars.index(el) + 1;
			stars
				.children('a').css('width', '100%').end()
				.slice(0,index).addClass('hover').addClass('editable').end();
		},
		drain: function() { // drain all the stars.
			stars
				.filter('.on').removeClass('on').end()
				.filter('.hover').removeClass('hover').end();
		},
		reset: function(){ // Reset the stars to the default index.
			stars.slice(0,settings.curvalue).addClass('on').end();
		}
	}
}



function showWidget( grid_id, id, trigger, width )
{
    var widget = $( '#' + id );
    var bar = $( '#' + grid_id + '_gadgets_bar' );
    var widget_event_switches = eval('widget_event_switches_'+grid_id);
    var widget_switches = eval('widget_switches_'+grid_id);
    var widget_triggers = eval('widget_triggers_'+grid_id);

    if( !widget_event_switches[id] )
    {
        widget.hover( function(){}, closeWidget );
        widget_event_switches[id] = true;
        widget_triggers[id] = trigger;
    }

    widget.css('width',width);
    widget.css('background','#99CCCC');
    widget.css('position','absolute');
    widget.css('left', $(trigger).offset().left);
    widget.css('top', bar.offset().top + bar.height() );

    if( widget_switches[id] )
    {
        $(trigger).removeClass('expanded');
        widget.slideUp('normal',function(){});
        widget_switches[id] = false;
    }
    else
    {
        for( widget_id in widget_switches )
        {
            if( widget_switches[widget_id] )
            {
                $(widget_triggers[widget_id]).removeClass('expanded');
                $('#'+widget_id).slideUp('normal',function(){});
                widget_switches[widget_id] = false;
            }
        }
        $(trigger).addClass('expanded');
        widget_switches[id] = true;
        widget.slideDown( 'normal', function(){} );
    }
}

function closeWidget()
{
    var td_id = $('#'+this.id).parent().attr('id');
    var grid_id = td_id.substr( 0, td_id.length - 11 );
    var widget_switches = eval('widget_switches_'+grid_id);
    var widget_triggers = eval('widget_triggers_'+grid_id);

    if( widget_switches[this.id] )
    {
        $('#'+this.id).slideUp('normal',function(){});
        widget_switches[this.id] = false;
        $(widget_triggers[this.id]).removeClass('expanded');
    }
}

