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.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>");
        $('html, body').animate({
            scrollTop:0
        }, 'slow');
        $.post($(this).attr('href'), {
            ajax_request: 1,
            options: 2
        }, 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');
        //Let's see if I have any wyzz area to be updated..
        //updateTextArea('body');
        var v = jQuery('#' + formId).validate({
            submitHandler: function(form){
                $('#' + formId + ' textarea[rel*=htmlTextEditor]').each(function(){
                    updateTextEditor($(this).attr('id'));
                });
                jQuery(form).ajaxSubmit({
                    target: "#" + formId + '_form_result',
                    data: ({
                        'ajax_request': 1 //You know this!!
                    }),
                    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;
    })
};
/**
 * 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') : 'tempOverLayDiv';
        $("#" + 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)
            });
        
        $.post($(this).attr('href'), {
            ajax_request: 1
        }, function(data){
            $("#" + div_name).html(data);
            initializeJqueryFunctions(div_name);

        })
        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//
    $('#' + divId + ' a[rel*=ajaxRequest]').makeLinkAjaxified();

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

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

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

    $('#' + divId + ' [rel*=alternateColorList]').makeAlternetColorList();


}
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;

}
$().ready(function(){
    initializeJqueryFunctions('');
});

//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(){
    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;

}

//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){
    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 + '/', {
                'id': rowId,
                ajax_request: 1
            }, function(data){
                $('#' + div_id).hide();
            });
        }, 3000);
        $('#'+div_id).append("<div id='delete_undo_"+ div_id+"'><a href='javascript:void(0)' onclick=\"stopDelete("+deleteTimer+",'"+div_id+"');\">Undo</a></div>");
    }
    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).html('');
}

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 updateTextEditor(textAreaId){
    //updateTextArea(textAreaId);
    var ckeditorInstanceString = 'CKEDITOR.instances.'+textAreaId;
    var ckEditor = eval(ckeditorInstanceString);
    $('#'+textAreaId).val(ckEditor.getData());

}

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){
    $("#" + div_name).html("<div class='loading'><img src='/img/gears_animated.gif' width='16px' height='16px' /> Loading, Please Wait..</div>");
    $.post(remoteUrl, {
        ajax_request: 1
    }, function(data){
        $("#" + div_name).html(data);
        initializeJqueryFunctions(div_name);
    });
}
