/*
  ======================================
  Globekey Universal Toggler
  ======================================
  Authors: Dave Probert
  Created: 10/12/2008 19:29:45
  Modified:
  ======================================
  Params:
    idref = a single #ID 
              or 
            a kref value (matching the last bit of a ktog_xxx - eg: 'xxx')
              or
            one of the above with a * postfix (eg. aaa* - this means change ALL tog items matching ktog_aaa...), the opt 'force' value should be set for these (see below)
              or 
            a space separated list of #ID's and/or krefs - eg: "abc #boo xyz aaa*"
    opts = optional JSON options object:
      *    effect = 'fade' | 'slide'
      *     speed = 'fast' | 'slow' | a millisecond number (eg. 600)
      *     force = 'none' | 'show' | 'hide'
*/
function krc_toggle(idref)
{
var opt       = arguments[1] || 0;
var trg       = idref.split(' ');
var img_path  = opt.imgpath || '/common/img/';
var img_show  = opt.imgshow || 'down_arrow.gif';
var img_hide  = opt.imghide || 'right_arrow.gif';
var txt_show  = opt.txtshow || 'Click to Show';
var txt_hide  = opt.txthide || 'Click to Hide';
var spd       = opt.speed || 'fast';
var force     = opt.force || 'none';  // or 'show' or 'hide'
  
  
  for(var i in trg)
  {
  var idr   = trg[i];
    
    if(idr.substr(idr.length-1, 1) == '*')
    {
      idr = idr.substr(0, idr.length-1);
      
      if(idr.substr(0,1) == '#')
      {
        var foo   = '[id^='+idr.substr(1)+']';
        var ext   = idr.substr(1).replace('ktog_', '');
        
        var _img  = '[id^=ktog_im_'+ext+']';
        var _txt  = '[id^=ktog_tx_'+ext+']';
      }
      else
      {
        var foo   = '[kref^=ktog_'+idr+']';
        var ext   = idr;
        
        var _img  = '[kref^=ktog_im_'+ext+']';
        var _txt  = '[kref^=ktog_tx_'+ext+']';
      }
    }
    else
    {
      if(idr.length>0)
      {
        // do the toggle here
        if(idr.substr(0,1) == '#')
        {
          var foo   = idr;
          var ext   = idr.substr(1).replace('ktog_', '');
          
          var _img  = '#ktog_im_'+ext;
          var _txt  = '#ktog_tx_'+ext;
        }
        else
        {
          var foo   = '[kref=ktog_'+idr+']';
          var ext   = idr;
          
          var _img  = '[kref=ktog_im_'+ext+']';
          var _txt  = '[kref=ktog_tx_'+ext+']';
        }
        //var foo = (idr.substr(0,1) == '#' ? idr : '[kref*=ktog_'+idr+']');
        //var ext = (idr.substr(0,1) == '#' ? idr.substr(1) : idr);
        var already_hidden = $(foo+':hidden').length > 0;
      }
    }
    
    if( force == 'show' ) already_hidden = true;
    if( force == 'hide' ) already_hidden = false;

    // dir is a flag of whether the item is hidden or not already
    if(already_hidden)
    { // SHOW
      switch(opt.effect)
      {
        case 'fade': $(foo).fadeIn(spd); break;
        case 'slide': $(foo).slideDown(spd); break;
        default: $(foo).show();
      }
      $(_img).attr( 'src', img_path+img_show ).attr( 'title', txt_hide ).attr( 'alt', txt_hide );
      $(_txt).html( txt_hide);
    }
    else
    { // HIDE
      switch(opt.effect)
      {
        case 'fade': $(foo).fadeOut(spd); break;
        case 'slide': $(foo).slideUp(spd); break;
        default: $(foo).hide();
      }
      $(_img).attr( 'src', img_path+img_hide ).attr( 'title', txt_show ).attr( 'alt', txt_show );
      $(_txt).html( txt_show );
    }
  }
}

//##=====================================================================================
//
//  DIALOG BOX FUNCTIONS
//
//##=====================================================================================
/*
  ======================================
  Globekey Dialog Box
  ======================================
  Authors: Mr O
  Created: 18/12/2008 16:43:28
  Modified:
  ======================================
  Example:
  <div id="krc_my_dialog"> foo </div>
  
  in script - before document ready:
  
  krc_dlg_construct('krc_my_dialog' [, opts]);
  Params:
    id = unique id for the DOM element to use as a dialog
            or a space separated list of #ID's and/or krefs - eg: "abc #boo xyz"
    opts = optional JSON options object:
      * keep_pos              = 'yes' | 'no'  Keep last position of dialog box default 'no'
      * draggable_enable      = 'yes' | 'no'  Enable dialog box draggable default 'yes'
      * close_button          = 'yes' | 'no'  Display close button at top right default 'yes'
      * force_overlap_left    = 'yes' | 'no'  Can drag to left position less than '0' default 'no'
      * force_overlap_top     = 'yes' | 'no'  Can drag to top position less than '0' default 'no'
      * force_overlap_right   = 'yes' | 'no'  Can drag overlap on right position default 'yes'
      * force_overlap_bottom  = 'yes' | 'no'  Can drag overlap on bottom position default 'yes'
      * backcover             = 'yes' | 'no'  Turn on backcover default 'no'
      * border_style          = number,  default `0`
*/
var krc_dlg_options     = [];     // Internal used
var krc_dlg_hide_on_esc = true;   // Hide dislog when hit ESCAPE   true | false
var krc_dlg_count       = 0;      // Internal used
var krc_dlg_backcover   = '';     // Internal used

$(document).ready( function()
{
  krc_dlg_init();
  
  //========== Hide all dialogs when hit ESC =====================
  if(krc_dlg_hide_on_esc)
    $(document).keypress( function(e) { if(e.keyCode == 27) krc_dlg_hide(); });
  //==================================================
  
  $(window).resize(krc_set_pos);
});


function krc_dlg_init()
{
  //if(!krc_dlg_options || krc_dlg_options.length==0) return;
  if( krc_dlg_count <= 0 ) return;
  /////////////////////////////////////////////////////////
  // Initial dialogbox data
  /////////////////////////////////////////////////////////
  for(var id in krc_dlg_options)
  {
    //=========== Border Style ============================
    if( krc_dlg_options[id].border_style > 0 )
    {
      var _h  = $('#'+id).html();
      var h   = '';
      
      h += "<table width='100%' border='0' cellspacing='0' cellpadding='0' class='border_style"+krc_dlg_options[id].border_style+"'>";
      h += "<thead><tr><td class='tl'></td><td class='tc'></td><td class='tr'></td></tr></thead>";
      h += "<tfoot><tr><td class='bl'></td><td class='bc'></td><td class='br'></td></tr></tfoot>";
      h += "<tbody><tr><td class='ml'></td><td bgcolor='#DDECFF'>";
      h += "<div id='"+id+"_style_content'>...</div></td><td class='mr'></td></tr></tbody>";
      h += "</table>";
      
      $('#'+id).html(h);
      $('#'+id+'_style_content').html(_h);
      
    }
    //=====================================================
    
    //========== Hide Dialog ==============================
    if( krc_dlg_options[id].close_button )
    {
      $('#'+id).append("<div class='kr_close_dialogbox' title='Close' alt='Close' ref='"+id+"'> X </div>");
      $('#'+id+' .kr_close_dialogbox')
        .css({
          'cursor':'pointer', 'color':'#FFF', 'font-size': '11px', 'font-weight': 'bold' , 'font-family':'Arial',
          'position':'absolute', 'width':'auto', 'top': '5px', 'left':$('#'+id).width()-18+'px','margin':'0'})
        .click( function() { krc_dlg_hide(this); });
    }
    //=====================================================
    
    //========== Dragable =================
    //=== Set Class is "kr_dialog_title" to handle bar for draggable
    //=== if not set the id all path of dialog box can drag
    if( krc_dlg_options[id].draggable_enable )
    {
      $('#'+id).draggable({ handle: '.kr_dialog_title', drag: krc_dlg_drag_event });
      $('#'+id).mousedown( function() { if( krc_dlg_options[id].draggable_enable ) $('#'+id).draggable( "enable" ); });
      $('#'+id).click( function() { $('#'+id).draggable( "disable" ); });
      krc_dlg_drag(id);
    }
  }
  
  krc_set_pos();
  
  if(krc_dlg_backcover != '')
  {
    var h = "<div id='"+krc_dlg_backcover+"' ";
    h += "style='position:absolute; left:0px; right:0px; top:0px; bottom:0px; background:black; opacity:.25; filter: alpha(opacity=25); -moz-opacity: 0.25; display:none; z-index:900; ";
    h += "height:"+$(document).height()+"px; width:"+$(document).width()+"px'></div>";
    $(document.body).append(h);
  }
}

function krc_set_pos()
{
  for(var id in krc_dlg_options)
  {
    krc_dlg_options[id].top   = ( $(window).height() / 2 ) - ( $('#'+id).height() / 2 );
    krc_dlg_options[id].left  = ( $(window).width() / 2 ) - ( $('#'+id).width() / 2 );
  }
  
  if(krc_dlg_backcover != '')
    $('#'+krc_dlg_backcover).css({'height': $(document).height()+'px', 'width': $(document).width()+'px'});
}
/**
// parameters:
// id = unique id for the DOM element to use as a dialog
// arguments[1] optional JSON options
*/
function krc_dlg_construct(id)
{
  var opt = arguments[1] || {};
  opt.draggable_enable      = (opt.draggable_enable     == 'no'  ? false : true);   // Enable dialog box draggable - default 'yes'
  opt.keep_pos              = (opt.keep_pos             == 'yes' ? true  : false);  // Keep last position of dialog box - default 'no'
  opt.keep_pos_opened       = false;                                                // Internal used for opt.keep_pos
  opt.close_button          = (opt.close_button         == 'no'  ? false : true);   // Display close button at top right - default 'yes'
  opt.force_overlap_left    = (opt.force_overlap_left   == 'yes' ? true  : false);  // Can drag to left position less than '0' - default 'no'
  opt.force_overlap_top     = (opt.force_overlap_top    == 'yes' ? true  : false);  // Can drag to top position less than '0' - default 'no'
  opt.force_overlap_right   = (opt.force_overlap_right  == 'no'  ? false : true);   // Can drag overlap on right position - default 'yes'
  opt.force_overlap_bottom  = (opt.force_overlap_bottom == 'no'  ? false : true);   // Can drag overlap on bottom position - default 'yes'
  opt.backcover             = (opt.backcover            == 'yes' ? true  : false);  // Turn on backcover - default 'no'
  opt.border_style          = (opt.border_style ? border_style : 0);                // Border style - default `0` [number]
  krc_dlg_hide_on_esc       = (opt.krc_dlg_hide_on_esc  == 'no'  ? false : true);  // Hide dislog when hit ESCAPE - default 'yes'
  
  krc_dlg_options[(id ? id : 'krc_dlg_div')] = opt;
  
  krc_dlg_count = 0;
  for( var i in krc_dlg_options)
    krc_dlg_count++;
  
  if(opt.backcover)
    krc_dlg_backcover = 'krc_dlg_backcover';
}

function krc_dlg_drag_event(event, ui)
{
  var id = event.target.id;
  if(!id) id = ui.helper[0].id;
  
  if(!krc_dlg_options[id].force_overlap_left && Number(ui.absolutePosition.left) < 0 )
    ui.position.left = 0;
  
  if(!krc_dlg_options[id].force_overlap_top && Number(ui.absolutePosition.top) < 0 )
    ui.position.top = 0;
  
  if( !krc_dlg_options[id].force_overlap_right && ($(window).width() - Number(ui.absolutePosition.left) - 2) <= $('#'+id).width() )
    ui.position.left = $(window).width() - $('#'+id).width() - 2;
  
  if( !krc_dlg_options[id].force_overlap_bottom && ($(window).height() - Number(ui.absolutePosition.top) - 2) <= $('#'+id).height() )
    ui.position.top = $(window).height() - $('#'+id).height() - 2;
}


function krc_dlg_drag(id)
{
  if( ! krc_dlg_options[id].draggable_enable ) return false;
  
  //========== Dragable =================================
  if( krc_dlg_options[id].draggable_enable )
  {
    $('#'+id).draggable( "enable" );
    $('#'+id+' .kr_dialog_title').css({cursor:'move'});
  }
  else
  {
    $('#'+id).draggable( "disable" );
    $('.kr_dialog_title').css({cursor:'default'});
  }
}

function krc_dlg_show(id, t, l)
{
  if( krc_dlg_options[id].keep_pos == false || krc_dlg_options[id].keep_pos_opened == false )
  {
    //=== t (top) and l (left) position of dialogbox
    //=== if t and l are not set dialogbox show at center of screen by default
    t = t || krc_dlg_options[id].top  + $(document).scrollTop();
    l = l || krc_dlg_options[id].left + $(document).scrollLeft();
    
    //=== if dialogbox over flow at bottom, move back in screen
    if( $(document).height() < ( t + $('#'+id).height() ) )
      t = $(document).height() - $('#'+id).height() - 20;
    
    //=== if dialogbox over flow at right, move back in screen
    if( $(document).width() < ( l + $('#'+id).width() ) )
      l = $(document).width() - $('#'+id).width() - 20;
      
    $('#'+id).css({left:l+'px', top:t+'px'});
    
    krc_dlg_options[id].keep_pos_opened = true;
  }
  $('#'+id).show();
  
  if($.browser.msie)
  {
    $('#'+id+' .kr_dialog_title').css({'width':$('#'+id).width()+'px'});
    $('#'+id+' .kr_close_dialogbox').css({'left':($('#'+id).width()-18)+'px'});
  }
  
  if(krc_dlg_options[id].backcover && krc_dlg_backcover != '')
  {
    $('#'+krc_dlg_backcover).css({'height': $(document).height()+'px', 'width': $(document).width()+'px'});
    $('#'+krc_dlg_backcover).show();
  }
}

function krc_dlg_hide(d)
{
  if(d)
  {
    id = $(d).attr('ref');
    //if( krc_dlg_options[id].draggable_enable ) $('#'+id).draggable( "disable" );
    $('#'+id).hide();
    
    if($.browser.msie)
      $('#'+id+' .kr_dialog_title').css({'width':'100%'});
  }
  else
  {
    for(var i in krc_dlg_options)
    {
      $('#'+i).hide();
      
      if($.browser.msie)
        $('#'+i+' .kr_dialog_title').css({'width':'100%'});
    }
  }
  
  if(krc_dlg_backcover != '')
    $('#'+krc_dlg_backcover).hide();
  
}

//##=====================================================================================
//
//  Valid Text FUNCTIONS
//
//##=====================================================================================
function krc_valid_text(s)
{
  var validchars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890, ";
  for (i=0; i < s.length; i++)
  {
    if(validchars.indexOf(s.charAt(i)) == -1)
      return false;
  }
  return true;
}
