/*
      ############################
     ##  Document Ready funcs  ##
    ############################
   #############################################################################
*/
// Global Variables //
var myWindowSize = null;
function onLoad(){
    init_pop('a.popbox'); // Apply the popbox routine
    initMCE("o2k7");     // Prepare tinyMCE for adding to a field
    myWindowSize = getWindowSize();
}

/*
 *##############################################################################
   ############################
  ##  General Functions     ##
 ############################
 #############################################################################
*/

function getWindowSize() {
    var myWidth = 0, myHeight = 0;
    if( typeof( window.innerWidth ) == 'number' ) {
        //Non-IE
        myWidth = window.innerWidth;
        myHeight = window.innerHeight;
    }
    else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
        //IE 6+ in 'standards compliant mode'
        myWidth = document.documentElement.clientWidth;
        myHeight = document.documentElement.clientHeight;
    }
    else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
        //IE 4 compatible
        myWidth = document.body.clientWidth;
        myHeight = document.body.clientHeight;
    }
//  window.alert( 'Width = ' + myWidth );
//  window.alert( 'Height = ' + myHeight );
    return {"width":myWidth,"height":myHeight}
}

function dynamic_load(display, data){
    $(display).load(data);
}

function dynamic_edit_users(index, html){
    var td = node.parentNode;
    var tr = getParent(td, "tr")
    $(tr).children()[0].innerHTML = html;
    $(tr).children()[1].innerHTML = html;
    $(tr).children()[2].innerHTML = html;
    $(tr).children()[3].innerHTML = html;
    $(tr).children()[5].innerHTML = html;
    $(tr).children()[6].innerHTML = html;
}

function expand(object, size){
    $("#"+object).stop();
    setTimeout("document.getElementById('"+object+"').style.display = 'block'", 1100);
    $("#"+object).animate({height: '+'+size+'px'}, 1000);
}

function shrink(object, size){
    $("#"+object).stop();
    $("#"+object).animate({height: '-'+size+'px'}, 1000);
    document.getElementById(object).innerHTML = "";
    setTimeout("document.getElementById('"+object+"').style.display = 'none'", 1100);
}

function toggleview(element1) {

   element1 = document.getElementById(element1);

   if (element1.style.display == 'block' || element1.style.display == '')
      element1.style.display = 'none';
   else
      element1.style.display = 'block';

   return;
}

function jumpMenu(targ,selObj,restore){
  eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
  if (restore) selObj.selectedIndex=0;
}
/*
 *##############################################################################
      ###############
     ##  Gallery  ##
    ###############
*/
$(function()
{
    $("#imageOptions a").click(function()
        {
        var imageSource = $(this).children("img").attr("src");
       
        $("#loader").addClass("loading");
        $("h3").remove();
          showImage(imageSource);
          return false;
        });
});


function showImage(src)
{
$("#loader img").fadeOut("normal").remove();
var largeImage = new Image();
$(largeImage).load(function()
                        {
                        $(this).hide();
                        $("#loader").append(this).removeClass("loading");
                                             
                        $(this).fadeIn("slow");              
                        });    
$(largeImage).attr("src", src);                                                                               
}
/*
 *##############################################################################
      ###############
     ##  TinyMCE  ##
    ###############
*/
function initTinyierMCE(skin){
    tinyMCE.init({
	    // General options
	    mode : "exact",
	    theme : "advanced",
	    skin : skin
//	    plugins :
    });
}

function initMCE(skin){
    tinyMCE.init({
	// General options
	mode : "exact",
	theme : "advanced",
	skin : skin,
	plugins : "advcode,safari,spellchecker,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,imagemanager,filemanager",

	// Theme options
	theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect",
	theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
	theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen,|,advcode",
	theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,spellchecker,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,blockquote,pagebreak,|,insertfile,insertimage",
	theme_advanced_toolbar_location : "top",
	theme_advanced_toolbar_align : "left",
	theme_advanced_statusbar_location : "bottom",
	theme_advanced_resizing : true

	// Example content CSS (should be your site CSS)
	//content_css : "css/example.css",

	// Drop lists for link/image/media/template dialogs
	//template_external_list_url : "resources/js/tinyMCE/template_list.js",
	//external_link_list_url : "resources/js/tinyMCE/link_list.js",
	//external_image_list_url : "resources/js/tinyMCE/image_list.js",
	//media_external_list_url : "resources/js/tinyMCE/media_list.js",

	// Replace values for the template plugin
	//template_replace_values : {
		//username : "Some User",
	//	staffid : "991234"
	//}
});
}
function attachMCE(element){
    tinyMCE.execCommand('mceAddControl', false, element);
}
function detachMCE(element){
    tinyMCE.execCommand('mceFocus', false, element);        
    tinyMCE.execCommand('mceRemoveControl', false, element);
}
/*
 *##############################################################################
      #################
     ##  Time Worx  ##
    #################
*/

function validateTime(date,iHour,iMinute,iAp,oHour,oMinute,oAp){
    var to_return = {};

    iHour = parseInt(iHour);
    iMinute = parseInt(iMinute);
    oHour = parseInt(oHour);
    oMinute = parseInt(oMinute);
    
    if (iAp == "PM"){
        iHour += 12;
    }
    if (oAp == "PM"){
        oHour += 12;
    }

    if (date == ""){
        to_return["error"]="You did not enter a date";
        to_return["status"] = false;
    }

    var given = date.split(" - ");
    
    var start_date = new Date();
    var start = given[0].split("-");
    start_date.setFullYear(start[0], start[1], start[2]);
    start_date.setHours(iHour, iMinute, 0, 0);

    var end_date = new Date();
    var end = given[1].split("-");
    end_date.setFullYear(end[0], end[1], end[2]);
    end_date.setHours(oHour, oMinute, 0, 0);
    
    if (start_date > end_date){
        to_return["error"]="Start date cannot be after the end date";
        to_return["status"] = false;
    }else if(end_date > start_date){
        to_return["status"] = true;  
    }
    
    return to_return;
}
/*
 *##############################################################################
      ###############
     ##  PopBox   ##
    ###############
*/
//add the popup box to the on-click of the <a> element
function init_pop(elems){
	$(elems).click(function(){
            var t = this.title || this.name || null;
            var a = this.href || this.alt;
            var g = this.rel || false;
            var queryString = a.replace(/^[^\?]+\??/,'');
            var popVars = parseQueryString(queryString);
            alert(popVars['height']+" "+popVars['width']);
            showPop(a ,popVars);
            this.blur();
            return false;
	});
}
function parseQueryString(query){
   var Params = {};
   if ( ! query ) {return Params;}// return empty object
   //var Pairs = query.split(/[;&]/);
   var Pairs = query.split(/[/]/);
   for ( var i = 0; i < Pairs.length; i++ ) {
      if (i < 2){ continue; }
      key = null;
      if (i == 2){ key = "height"; }
      if (i == 3){ key = "width"; }
      if (i == 4){ key = "modal"; }
      var KeyVal = Pairs[i];
      if ( ! KeyVal ) {continue;}
      var val = unescape( KeyVal );
      val = val.replace(/\+/g, ' ');
      Params[key] = val;
   }
   return Params;
}
function makeDiv(id,cls,where){
    var nDiv = document.createElement('div');
    nDiv.setAttribute('id', id);
    nDiv.setAttribute('class', cls);
    $(where).append(nDiv);
}

function showPop(url,paramSet){
    var params = {
        'width':200,
        'height':50,
        'modal':false
    }
    if (typeof(paramSet) == 'undefined' || paramSet==''){
        var queryString = url.replace(/^[^\?]+\??/,'');
        params = parseQueryString(queryString);
    }else{
        params = paramSet;
    }
    if (($("#popBack").length < 1) && ($("#popContent").length < 1) ){
        // Create the divs for the popup
        makeDiv('popBack','popBack','body');
        makeDiv('popContent','popContent','body');
        // If not modal then make it "click anywhere to close"
        if (!params['modal']){
            $("#popBack").attr("onClick","hidePop();");
        }
        // Display the background
        $("#popBack").fadeIn("fast",function (data){
	    $("#popBack").css('filter', 'alpha(opacity=80)');
            // Set up the content window dimensions
            var pop =  $("#popContent");
            pop.width(parseInt(params['width']));
            pop.height(parseInt(params['height']));
            pop.css("margin-top", -parseInt(params['height']) / 2 + "px");
            pop.css("margin-left", -parseInt(params['width']) / 2 + "px");
            // Display the content window
            var getVars = {}
            $.get(url,getVars,function(data){
                    pop.html(data);
                },'html');
            // Fill in the content window!
            pop.slideToggle("slow", function (data){});
        });
    }
}
function hidePop(){
    // Empty it out first!
    $("popContent").empty();
    // Start by closing the content box
    $("#popContent").slideToggle("fast",function (data){
        // Once hidden hide the background div
        $("#popBack").fadeOut("fast",function (data){
            // Cleanup! Delete the now unused divs.
            $("#popContent").remove();
            $("#popBack").remove();
        });
    });
}

function getParent(el, pTagName) {
	if (el === null) {
	    return null;
	} else {
            if (el.nodeType == 1 && el.tagName.toLowerCase() == pTagName.toLowerCase()) {
                return el;
            } else {
                return getParent(el.parentNode, pTagName);
            }
	}
}

function changeTab(tab,group){
    var vis = $("div[@name="+group+"]:visible");
    var ani = $("div[@name="+group+"]:animated");
    if(vis.length == 1 && ani.length < 1){
        var id = vis.attr('id');
        $("#"+id).slideToggle("slow", function(){
            if (id != tab){
                $('#t'+tab).addClass('hover');
                $("#"+tab).slideToggle("slow");
            }
        });
    }else if(vis.length < 1 && ani.length < 1){
        $('#t'+tab).addClass('hover');
        $("#"+tab).slideToggle("slow");
    }
}

