String.prototype.trim = function() {
   return this.replace(/^\s+|\s+$/g, '');
};

var pb_common = {

   date_format : '%m/%d/%Y %H:%M:%S',

   datetime_format : '%m/%d/%Y %H:%M:%S',

   loggedin : false,

   fb_loggedin : false,

   fb_uid : null,

   redirect : function(to, text) {
      var t = (text ? text : 'Loading');
      document.write('<div style="margin-top:50px;text-align:center;font-family:sans-serif;text-decoration:blink;font-size:20px;font-weight:bold;color:#ACC9E5;">&raquo;&raquo;&raquo; '+t+' &raquo;&raquo;&raquo;</div>');
      window.location=to;
   },

   isArray : function (obj) {
      if (obj) {
         if (obj.constructor.toString().indexOf('Array') == -1)
            return false;
         else
            return true;
      }
      return false;
   },

   isForm : function (obj) {
      if (obj) {
         if (obj.constructor) {
            if (obj.constructor.toString().indexOf('Form') == -1)
               return false;
            else
               return true;
         } else {
            return obj.tagName == 'FORM';
         }
      }
      return false;
   },

   getCookie : function (name) {
      var start = document.cookie.indexOf(name+'=');
      var len = start+name.length+1;
      if ((!start) && (name != document.cookie.substring(0,name.length))) return null;
      if (start == -1) return null;
      var end = document.cookie.indexOf(';',len);
      if (end == -1) end = document.cookie.length;
      return unescape(document.cookie.substring(len,end));
   },

   setCookie : function (name,value,expires,path,domain,secure) {
      expires = expires * 60*60*24*1000;
      var val;

      if (this.isArray(value))
         val = value.join(',');
      else
         val = value;

      var today = new Date();
      var expires_date = new Date( today.getTime() + (expires) );
      var cookieString = name + '=' +escape(val) +
         ( (expires) ? ';expires=' + expires_date.toGMTString() : '') +
         ( (path) ? ';path=' + path : '') +
         ( (domain) ? ';domain=' + domain : '') +
         ( (secure) ? ';secure' : '');
      document.cookie = cookieString;
   },

   parseDate : function(str, fmt) {
      var today = new Date();
      var y = 0;
      var m = -1;
      var d = 0;
      var a = str.split(/\W+/);
      var b = fmt.match(/%./g);
      var i = 0, j = 0;
      var hr = 0;
      var min = 0;
      var sec = 0;
      for (i = 0; i < a.length; ++i) {
         if (!a[i]) continue;
         switch (b[i]) {
            case "%d": case "%e": d = parseInt(a[i], 10); break;

            case "%m": m = parseInt(a[i], 10); break;

            case "%Y": case "%y": y = parseInt(a[i], 10); (y < 100) && (y += (y > 29) ? 1900 : 2000); break;

            /* requires Calendar control to parse %b and %B masks */
            /*
            case "%b": case "%B":
               for (j = 0; j < 12; ++j) {
                  if (Calendar._MN[j].substr(0, a[i].length).toLowerCase() == a[i].toLowerCase()) { m = j; break; }
               }
               break;
            */

            case "%H": case "%I": case "%k": case "%l": hr = parseInt(a[i], 10); break;

            case "%P": case "%p":
               if (/^pm$/i.test(a[i])) {
                  if (hr < 12) hr += 12;
               } else if (/^am$/i.test(a[i])) {
                  if (hr >= 12) hr -= 12;
               } else {
                  return false;
               }
               break;

            case "%M": min = parseInt(a[i], 10); break;

            case "%S": sec = parseInt(a[i], 10);
         }
      }
      if (isNaN(y) || isNaN(m) || isNaN(d)) return false;
      if (isNaN(hr)) hr = today.getHours();
      if (isNaN(min)) min = today.getMinutes();
      if (isNaN(sec)) sec = today.getSeconds();
      if (y != 0 && m != -1 && d != 0)
         return new Date(y, m, d, hr, min, sec);
      return false;
   },

   parseInt : function(x) { x = parseInt(x); return isNaN(x) ? 0 : x; },

   parseFloat : function(x) { x = parseFloat(x); return isNaN(x) ? .0 : x; },

   convert : function(value, type) {
      switch (type) {
         case 'int' : return this.parseInt(value);
         case 'float' : return this.parseFloat(value);
         case 'date' : return parseDate(value, this.date_format);
         case 'datetime' : return parseDate(value, this.datetime_format);
         default : return (value) ? value.toString() : '';
      }
   },

   time_since :function (original_timestamp) {
      if (original_timestamp && !isNaN(original_timestamp)) {
         // array of time period chunks
         var chunks = [
            [60 * 60 * 24 * 365 , 'year'],
            [60 * 60 * 24 * 30 , 'month'],
            [60 * 60 * 24 * 7, 'week'],
            [60 * 60 * 24 , 'day'],
            [60 * 60 , 'hour'],
            [60 , 'minute'],
         ];
         var since = this.timestamp() - original_timestamp, i, j, sc, nm, c;
         for (i = 0, j = chunks.length; i < j; i++) {
            sc = chunks[i][0];
            nm = chunks[i][1];
            // finding the biggest chunk (if the chunk fits, break)
            c = Math.floor(since / sc);
            if (c != 0) break;
         }
         p = ((c == 1) ? '1 '+nm : c+' '+nm+'s');
         if (i + 1 < j) {
            // now getting the second item
            var sc2 = chunks[i + 1][0];
            var nm2 = chunks[i + 1][1];
            // add second item if it's greater than 0
            var c2 = Math.floor((since - sc * c) / sc2);
            if (c2 != 0) {
               p += (c2 == 1) ? ', 1 '+nm2 : ', '+c2+' '+nm2+'s';
            }
         }
         return p + " ago";
      }
      return '';
   },

   timestamp :function () {
      return Math.floor((+ new Date())/1000);
   },

   timestamp2date :function (timestamp) {
      var d = new Date(timestamp * 1000), mm = d.getMonth()+1;
      return (mm < 10 ? '0'+mm : mm)+"/"+d.getDate()+"/"+d.getFullYear();
   },

   timestamp2time :function (timestamp, ampm) {
      var d = new Date(timestamp * 1000), hr = d.getHours(), min = d.getMinutes(), sec = d.getSeconds();
      if (ampm) {
         var h = (hr > 12 ? hr - 12 : hr);
         h = (h < 10 ? '0'+h : h);
         return h+':'+(min < 10 ? '0'+min : min)+':'+(sec < 10 ? '0'+sec : sec)+(hr >= 12 ? ' PM' : ' AM');
      } else {
         return hr+":"+(min < 10 ? '0'+min : min)+":"+(sec < 10 ? '0'+sec : sec);
      }
   },

   date2timestamp : function (year, month, day, hour, min, sec) {
      return (Date.UTC(year, month-1, day, hour, min, sec) / 1000);
   },

   getCSSStyle : function (e) {
      if (e) {
         if (e.currentStyle) return e.currentStyle;
         else if (window.getComputedStyle) return window.getComputedStyle(e, null)
      }
   },

   getPosition : function (e) {
      var left = 0;
      var top = 0;
      if (e.offsetParent) {
         left = e.offsetLeft;
         top = e.offsetTop;
         while (e = e.offsetParent) {
            var s = this.getCSSStyle(e);
            if (s.position == 'absolute' || s.position == 'fixed') break;
            left += e.offsetLeft;
            top += e.offsetTop;
         }
      }
      return [left, top];
   },

   scrollToEl : function (e) {
      if (e) {
         var t = $(e).offset().top;
         $('html,body').animate({scrollTop: t}, 'slow', 'swing');
      }
   },

   getEventTarget : function (evt) {
      var targ = (evt.target) ? evt.target : evt.srcElement;
      if (targ) if (targ.nodeType == 3) targ = targ.parentNode;
      return targ;
   },

   clickedOutsideElement : function (el, evt) {
      var theElem = pb_common.getEventTarget(evt);
      while (theElem) {
         if (theElem == el) return false;
         theElem = theElem.parentNode;
      }
      return true;
   },

   locationDlg: function(){
      $('#location_dlg').dialog('open').show();
   },

   fbLinkDlg: function(){
      $('#fb_link_dlg')
      .dialog('option', 'buttons', {
         'Yes, Associate': function(){
            pb_common.setCookie('partybody[ignore_fb_link_'+FB.Facebook.apiClient.get_session().uid+']', ($(this).find('#ignore_fb_link').get(0).checked ? 1 : 0), 500, '/');
            $(this).hide().dialog('close');
            pb_common.fblink();
         },
         No: function(){
            pb_common.setCookie('partybody[ignore_fb_link_'+FB.Facebook.apiClient.get_session().uid+']', ($(this).find('#ignore_fb_link').get(0).checked ? 1 : 0), 500, '/');
            $(this).hide().dialog('close');
         }
      })
      .dialog('open').show();
   },

   alert: function(text, showtime){
      $('#alert_dlg .body').html(text);
      $('#alert_dlg').dialog('open').show();
      if (showtime) {
         setTimeout(function(){
            $('#alert_dlg').parents('.ui-dialog:first').fadeOut('slow', function(){ $('#alert_dlg').dialog('close'); });
         }, showtime);
      }
   },

   progressStart: function(text, caption){
      $('#progress_dlg .body').text(text);
      if (caption) $('#progress_dlg').get(0).title = caption;
      $('#progress_dlg').dialog('open').show();
   },

   progressStop: function(){
      $('#progress_dlg').dialog('close').hide();
   },

   confirm: function(text, onyes, onno){
      $('#confirm_dlg .body').html(text);
      $('#confirm_dlg')
      .dialog('option', 'buttons', {
         Yes: function(){ onyes(); $(this).hide().dialog('close'); },
         No: (onno ? function(){ onno(); $(this).hide().dialog('close'); } : function(){ $(this).hide().dialog('close'); })
      })
      .dialog('open').show();
   },

   fblink: function(){
      //$('#friendprogress').dialog('open').show();
      $.ajax({
         type: 'POST',
         url: pb_common.base_url+'_ajax/fb_link.php',
         //data: 'uid='+uid,
         success: function(msg){
            eval('var d = '+msg);
            if (d.status=='ok') {
               pb_common.alert('Associated successfully', 3000);
               pb_common.fb_uid = FB.Facebook.apiClient.get_session().uid;
               $('#fb_associate').hide();
               if (load_fblinks) load_fblinks();
            } else {
               alert(d.data);
            }
         },
         error: function(){ alert('Error server response'); },
         complete: function(){ /*$('#friendprogress').dialog('close').hide();*/ }
      });
   },

   fbunlink: function(uid, cb){
      //$('#friendprogress').dialog('open').show();
      $.ajax({
         type: 'POST',
         url: pb_common.base_url+'_ajax/fb_unlink.php',
         data: 'uid='+uid,
         success: function(msg){
            eval('var d = '+msg);
            if (d.status=='ok') {
               pb_common.alert('Association removed', 3000);
               if (pb_common.fb_uid == uid) {
                  pb_common.fb_uid = null;
                  $('#fb_associate').show();
               }
               if (cb) cb(uid);
            } else {
               alert(d.data);
            }
         },
         error: function(){ alert('Error server response'); },
         complete: function(){ /*$('#friendprogress').dialog('close').hide();*/ }
      });
   },

  limitChars : function (textid, limit, infodiv){
      var text = $('#'+textid).val();

      var textlength = text.length;

      $('#' + infodiv)
      .each(function(){ this.className = this.className.replace(' warn', '') + (limit - textlength < 0 ? ' warn' : '') })
      .html((limit - textlength)+' ');

      /*if(textlength > limit) {
         $('#' + infodiv).html('You cannot write more then '+limit+' characters!');
         $('#'+textid).val(text.substr(0,limit));
         return false;
      } else {
         return true;
      }*/
      return true;
   },

   ajax : function (s) {
      if (s.progress_text) pb_common.progressStart(s.progress_text);

      $.ajax({
         type: 'POST',
         url: s.url,
         data: s.data,
         success: function(msg){
            if (s.progress_text) pb_common.progressStop();
            try {
               if (s.json) {
                  eval('var d = '+msg);
                  if (d.status == 'error') {
                     pb_common.alert(d.data);
                  } else {
                     s.callback(d);
                  }
               } else {
                  s.callback(d);
               }
            } catch (e) {
               pb_common.alert('Error server response...');
            }
         },
         error: function(){
            if (s.progress_text) pb_common.progressStop();
            pb_common.alert('Error server response');
         }
      });
   }

}

$(document).ready(function(){
   //set dialog default settings
   $.ui.dialog.defaults.bgiframe = true;
   $.ui.dialog.defaults.autoOpen = false;
   $.ui.dialog.defaults.resizable = false;
   $.ui.dialog.defaults.modal = true;
   $.ui.dialog.defaults.overlay = { backgroundColor: '#000', opacity: 0.2 };
   $.ui.dialog.defaults.height = 125;
   $.ui.dialog.defaults.width = 310;
   $.ui.dialog.defaults.open = function(event, ui) {
      var b = $(this).parents('.ui-dialog:first').find('.ui-dialog-buttonpane button').get(0);
      if (b) b.focus();
   };

   $('#location_dlg').dialog({
      buttons:{
         'Select >>': function(){
            var v = $(this).find('select[name=location]').eq(0).val();
            $(this).hide().dialog('close');
            var t = $(this).find('select[name=location] option[selected]').text();
            pb_common.redirect(v, 'Proceed to location '+t);
         },
         Cancel: function(){ $(this).hide().dialog('close'); }
      }
   });

   $('#confirm_dlg').dialog({height: 135});

   $('#progress_dlg').dialog({height: 90, width: 300});

   $('#fb_link_dlg').dialog({height: 195, width: 360});

   $('#alert_dlg').dialog({
      buttons:{ Ok: function(){ $(this).hide().dialog('close'); } }
   });

});
