/*
*  Written By Aanand Kumar Sharma.
*/



(function($) {
 
 //addsns
 
                       
                        $('.addTimeZone').live('click',function(e)
                        {
                        
                            if($('#hdnAddClock').val() != '2')
                            {
                                //alert('You do not have permission to create new clock.');
                                jAlert('You do not have permission to create new clock.', 'Alert Dialog',function(r){if(r == true){}});
                                return false;
                            }
                            
                            if($('.dvClock').length > 4)
                            {
                                //alert('You cannot have more than 5 clocks');
                                jAlert('You cannot have more than 5 clocks.', 'Alert Dialog',function(r){if(r == true){}});
                                return false;
                            }
                            
                            if($('.addTimeZoneBg').length > 1)
                            {
                                
                                return false;
                            }
                                
                            $.ajax(
                                {  
                                    type: "POST",
                                    url: 'zoneclock.aspx?zclk=1',  // Send the login info to this page
                                    data: { msg : '' },    //equivalent to url parameter "msg=Hellow%20Nurse!"
                                    async: true,    //default is asynchronous request can set to false
                                    cache: false,
                                    success: function(data)
                                    {  
                                        $('body').append(data);
                                        $('.addTimeZoneBg').css('top', 150).css('left',300).draggable({containment:'document',scroll: false});;
                                        
                                    }
                                });  
                        });
                        
                        $('.closeTimeZone').live('click',function(e)
                        {
                            var obj1 = $(this);
                            var val = $(this).attr('rel');
                            
                            jConfirm('Do you really want to close this clock?', 'Confirm Dialog',
                            function(r)
                            {
                                if(r)
                                {
                                    $.ajax(
                                    {  
                                        type: "POST",
                                        url: 'zoneclock.aspx',  // Send the login info to this page
                                        data: { onoff : val },    //equivalent to url parameter "msg=Hellow%20Nurse!"
                                        async: true,    //default is asynchronous request can set to false
                                        cache: false,
                                        success: function(data)
                                        {  
                                            $('.dvClock[rel=' + val + ']').remove();
                                            $('.clickWrapperInside').css('width', (parseInt($('.clickWrapperInside').css('width')) - 200));
                                        }
                                    });  
                                }
                                else
                                {
                                    return false;
                                }
                            });
                            
                            
                        });
                        
                        
                       $('a[name=addclock]').live('click',function()
                       {
                            
                            if(!validate(this.name))
                            {
                                return false;
                            }
                          
                            var el;
                            var dtSend='';
                            var obj = this;
                            el = document.getElementsByName('addclock');//take all runtime generated html control based on name
                            for(i=0; i<el.length; i++)
                            {
                               
                                if(el[i].type == 'select-one')
                                {
                                    dtSend += el[i].id + "~" + el[i].options[el[i].selectedIndex].value+ "~" + $(el[i].options[el[i].selectedIndex]).text();
                                    dtSend += ",";
                                }
                                
                            }
                
                            $.ajax({
                                        type: "POST",     //GET, POST
                                        url: "zoneclock.aspx",           //Specify the page your requesting
                                        data: { insert : dtSend },                  //equivalent to url parameter "msg=Hellow%20Nurse!" dtsend only we sending data by control or somethng else
                                        async: true,                            //default is asynchronous request can set to false
                                        cache: false,                          //default is false
                                        beforeSend:function()
                                        {
                                           //$('.main').showoverlay({imgPath:'JSOS/elapsor.gif', topX:0, topY:0});     
                                        },
                                        success: function(data)                  //returning data which return from cs file
                                        {  
                                            var finalResult = data.split('~');  //take ~ than finalresult become array
                                            if(finalResult.length > 1 && finalResult[0] == 'success')          //length means how many string contain this array after split
                                            {
                                             
                                               var ele1 = document.getElementById('ddlZone');
                                               CreateClock(ele1.options[ele1.selectedIndex].value,$(ele1.options[ele1.selectedIndex]).text(), finalResult[1]);
                                               $(obj).parent().parent().parent().remove();
                                            }
                                            else
                                            {
                                               //alert(finalResult[1]);
                                               jAlert(finalResult[1], 'Alert Dialog',function(r){if(r == true){}});
                                            }  
                                                      
                                        } 
                        
                                    });
                     });
                     
                     //till here
            
          
                
               //start On Off process 
                        //subonoff
                
                
                
 	var jqClockZIndex = 100;
    
  $.fn.jclock = function(options) {
    var version = '2.3.0';
 
    // options
    var opts = $.extend({}, $.fn.jclock.defaults, options);
         
    return this.each(function() {
    
    var clockMouseX = 0;
    var clockMouseY = 0;
        
      $this = $(this);
      $this.timerID = null;
      $this.running = false;
 
      // Record keeping for seeded clock
      $this.increment = 0;
      $this.lastCalled = new Date().getTime();
 
      var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
 
      $this.format = o.format;
      $this.utc = o.utc;
      // deprecate utc_offset (v 2.2.0)
      $this.utcOffset = (o.utc_offset != null) ? o.utc_offset : o.utcOffset;
      $this.seedTime = o.seedTime;
      $this.timeout = o.timeout;
      $this.htmll = o.html;
      $this.del = o.del;
 
      $this.css({
        fontFamily: o.fontFamily,
        fontSize: o.fontSize,
        backgroundColor: o.background,
        color: o.foreground
      });
      
      
      //==================
      
        
      
      //===================
 
      // %a
      $this.daysAbbrvNames = new Array(7);
      $this.daysAbbrvNames[0] = "Sun";
      $this.daysAbbrvNames[1] = "Mon";
      $this.daysAbbrvNames[2] = "Tue";
      $this.daysAbbrvNames[3] = "Wed";
      $this.daysAbbrvNames[4] = "Thu";
      $this.daysAbbrvNames[5] = "Fri";
      $this.daysAbbrvNames[6] = "Sat";
 
      // %A
      $this.daysFullNames = new Array(7);
      $this.daysFullNames[0] = "Sunday";
      $this.daysFullNames[1] = "Monday";
      $this.daysFullNames[2] = "Tuesday";
      $this.daysFullNames[3] = "Wednesday";
      $this.daysFullNames[4] = "Thursday";
      $this.daysFullNames[5] = "Friday";
      $this.daysFullNames[6] = "Saturday";
 
      // %b
      $this.monthsAbbrvNames = new Array(12);
      $this.monthsAbbrvNames[0] = "Jan";
      $this.monthsAbbrvNames[1] = "Feb";
      $this.monthsAbbrvNames[2] = "Mar";
      $this.monthsAbbrvNames[3] = "Apr";
      $this.monthsAbbrvNames[4] = "May";
      $this.monthsAbbrvNames[5] = "Jun";
      $this.monthsAbbrvNames[6] = "Jul";
      $this.monthsAbbrvNames[7] = "Aug";
      $this.monthsAbbrvNames[8] = "Sep";
      $this.monthsAbbrvNames[9] = "Oct";
      $this.monthsAbbrvNames[10] = "Nov";
      $this.monthsAbbrvNames[11] = "Dec";
 
      // %B
      $this.monthsFullNames = new Array(12);
      $this.monthsFullNames[0] = "January";
      $this.monthsFullNames[1] = "February";
      $this.monthsFullNames[2] = "March";
      $this.monthsFullNames[3] = "April";
      $this.monthsFullNames[4] = "May";
      $this.monthsFullNames[5] = "June";
      $this.monthsFullNames[6] = "July";
      $this.monthsFullNames[7] = "August";
      $this.monthsFullNames[8] = "September";
      $this.monthsFullNames[9] = "October";
      $this.monthsFullNames[10] = "November";
      $this.monthsFullNames[11] = "December";
 
      $.fn.jclock.startClock($this);
 
    });
  };
       
  $.fn.jclock.startClock = function(el) {
    $.fn.jclock.stopClock(el);
    $.fn.jclock.displayTime(el);
  }
 
  $.fn.jclock.stopClock = function(el) {
    if(el.running) {
      clearTimeout(el.timerID);
    }
    el.running = false;
  }
 
  $.fn.jclock.displayTime = function(el) {
    var time = $.fn.jclock.getTime(el);
    el.html(time);
    el.timerID = setTimeout(function(){$.fn.jclock.displayTime(el)},el.timeout);
  }
 
  $.fn.jclock.getTime = function(el) {
    if(typeof(el.seedTime) == 'undefined') {
      // Seed time not being used, use current time
      var now = new Date();
    } else {
      // Otherwise, use seed time with increment
      el.increment += new Date().getTime() - el.lastCalled;
      var now = new Date(el.seedTime + el.increment);
      el.lastCalled = new Date().getTime();
    }
 
    if(el.utc == true) {
      var localTime = now.getTime();
      var localOffset = now.getTimezoneOffset() * 60000;

      var utc = localTime + localOffset;
      var utcTime = utc + (3600000 * el.utcOffset);
 
      now = new Date(utcTime);


    }
 
       var timeNow = "";
       var hour   = now.getHours();
       var minute = now.getMinutes();
       var second = now.getSeconds();
       var day    =  now.toLocaleDateString();
       var ap = "AM";
       if (hour   > 11) { ap = "PM";             }
       if (hour   > 12) { hour = hour - 12;      }
       if (hour   == 0) { hour = 12;             }
       if (hour   < 10) { hour   =hour;   }
       if (minute < 10) { minute = "0" + minute; }
       if (second < 10) { second = "0" + second; }
       timeNow = ' <div class="timeWrapper"><span class="displayDate">' + day + '</span><br /><span class="displayTime">' + hour + ':' + minute + " " + ap + '</span><br /><span class="displayZone">' + el.htmll + '</span></div><div rel="' + el.del + '"  class="closeTimeZone" title="Close"><img src="images/spacer.gif" width="18" height="18" alt="" /></div>';
    /*var i = 0;
    var index = 0;
    while ((index = el.format.indexOf("%", i)) != -1) {
      timeNow += el.format.substring(i, index);
      index++;
 
      // modifier flag
      //switch (el.format.charAt(index++)) {
      //}
      
      var property = $.fn.jclock.getProperty(now, el, el.format.charAt(index));
      index++;
      
      //switch (switchCase) {
      //}
 
      timeNow += property;
      i = index
    }
 
    timeNow += el.format.substring(i);*/
    
    return timeNow;
  };
 
  $.fn.jclock.getProperty = function(dateObject, el, property) {
 
    switch (property) {
      case "a": // abbrv day names
          return (el.daysAbbrvNames[dateObject.getDay()]);
      case "A": // full day names
          return (el.daysFullNames[dateObject.getDay()]);
      case "b": // abbrv month names
          return (el.monthsAbbrvNames[dateObject.getMonth()]);
      case "B": // full month names
          return (el.monthsFullNames[dateObject.getMonth()]);
      case "d": // day 01-31
          return ((dateObject.getDate() < 10) ? "0" : "") + dateObject.getDate();
      case "H": // hour as a decimal number using a 24-hour clock (range 00 to 23)
          return ((dateObject.getHours() < 10) ? "0" : "") + dateObject.getHours();
      case "I": // hour as a decimal number using a 12-hour clock (range 01 to 12)
          var hours = (dateObject.getHours() % 12 || 12);
          return ((hours < 10) ? "0" : "") + hours;
      case "m": // month number
          return (((dateObject.getMonth() + 1) < 10) ? "0" : "") + (dateObject.getMonth() + 1);
      case "M": // minute as a decimal number
          return ((dateObject.getMinutes() < 10) ? "0" : "") + dateObject.getMinutes();
      case "p": // either `am' or `pm' according to the given time value,
          // or the corresponding strings for the current locale
          return (dateObject.getHours() < 12 ? "am" : "pm");
      case "P": // either `AM' or `PM' according to the given time value,
          return (dateObject.getHours() < 12 ? "AM" : "PM");
      case "S": // second as a decimal number
          return ((dateObject.getSeconds() < 10) ? "0" : "") + dateObject.getSeconds();
      case "y": // two-digit year
          return dateObject.getFullYear().toString().substring(2);
      case "Y": // full year
          return (dateObject.getFullYear());
      case "%":
          return "%";
    }
 
  }
       
  // plugin defaults (24-hour)
  $.fn.jclock.defaults = {
    format: '%H:%M:%S',
    utcOffset: 0,
    utc: false,
    fontFamily: '',
    fontSize: '',
    foreground: '',
    background: '',
    seedTime: undefined,
    timeout: 1000, // 1000 = one second, 60000 = one minute
    html:'',
    del:''
  };
 
})(jQuery);

var clockX = 80;
var clockY = 175;

function CreateClock(t,c,d)
{
    
    var cCount= $('.dvClock').length;
    if(cCount > 4)
        return;
        
    var options = {format: '%A %B %d, %Y %I:%M:%S %p',utc: true, utcOffset: t, html : c, del: d}
   
    var _div_Clock = $(document.createElement('div')).addClass('dvClock').attr('rel',d);
    _div_Clock.jclock(options);
    $('.clickWrapperInside').css('width', (parseInt($('.clickWrapperInside').css('width')) + 200));//.append(_div_Clock);
    if(cCount % 2 > 0)
    {
        _div_Clock.insertBefore($('#dvClockLocal'));
    }
    else
    {
        _div_Clock.insertAfter($('#dvClockLocal'));
    }
    AddEventForClock();
    
}
