/*
** Calls an action and loads returning html (which could be a form) into a popup (via facebox)
** link = 'this' (ie. yPopup(this,... )
** url  = path to controller/action other than the current controller's new action
**
** msg  = returning html (eg. new form, etc.)
**
** yPopup takes an optional 3rd argument
**   if 3rd arg is json (eg. {user_id: 1, dest: 'view'})
**     it is passed as datain the axaj call
**     'id' must be passed on the end of the url (.../id)
**
**   if 3rd arg is a string (or json with key {klass: ...} )
**     it is treated as a css class and passed to $.facebox
**
**   NOTE: if 3rd arg == 'inline' or has key {klass: 'inline', ...}
**      $.facebox will check for 'click-away' and close
*/
function yPopup(link,url){
  var u = url == null ? "new" : url;
  var d = arguments[2] ? arguments[2] : {}; // nginx needs this to be blank or it gives a 411 error

  if(link) link.disabled = true;

  // IE 6?
  var ie6 = $.browser.msie && /MSIE 6.0/.test(navigator.userAgent)

  // class to pass to facebox
  var klass = 'no-class';
  if(!d==''){
    if(typeof d === 'object'){
      if(d.klass){ klass = d.klass; }
    } else {
      var seed = new Date();
      seed = seed.getMilliseconds();
      klass = d;
      d = {_: seed};
    }
  }

  // .block() content unless 'inline'
//  if(!(klass=='inline')&&!ie6){ $('#content').block('<div id="loading_f" class="loading">Loading ... <img src="/images/loading.gif"/></div>'); }


  $.ajax({
        type: "POST",
        url: u,
        data: d,
        beforeSend: function(xhr) {xhr.setRequestHeader("Accept", "text/javascript");},
        error:function(xhr, status, errorThrown) {
          //if(status=='parsererrorz') {
          //  $.facebox(xhr.responseText,klass);
          //} else {
            //alert('{errorThrown: '+errorThrown+', status: '+status+', statusText: '+xhr.statusText);
            alert('An error has occurred in the javascript on this page');
          //}
        },
        success: function(msg){
          //$('#loading_f').parent('.blockUI').hide();
          $.facebox(msg,klass);
        },
        complete: function(){
          if(link) $(link).removeAttr('disabled');
          formEffects();
        }
    });

/*
    // the old-fashoned way
    var xmlhttp = false;
    if (window.XMLHttpRequest) {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
        xmlhttp.open("POST",u,false);
        xmlhttp.setRequestHeader("Content-type", "text/json; charset=UTF-8"); //'application/x-www-form-urlencoded;charset=ISO-8859-1');
        xmlhttp.send('?_=' + seed);
    } else {
        // code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        xmlhttp.open("POST",u,false);
        // Do not send null for ActiveX
        xmlhttp.send(d);
    }
    //alert("xmlhttp.responseText : " + xmlhttp.responseText);
    $.facebox(xmlhttp.responseText,klass);
*/
}

/*
** function yUpdate(link,target,data) [... action,ind)] see NOTE
**   link   => reference to link or button calling the function (Note: always "this")
**   target => id of target or array of target ids or the words "export" or "popup"
**   data   => "get" string or json data to pass to action (optional)
**             If data is a json object and has an element {form: ...},
**             then the form (or forms if it is an array) is serialized
**             and added to the other elements
**   action => the url for the controller action to be called by the function
**   ind    => id of the indicator (optional)
**
** NOTE: "action" and "indicator" can be included in the arguments (after data) or
**  the link calling the function can have an "action" and "indicator" attribute
**  (eg. <a action="..." indicator="..." onclick="yUpdate(this,... )
**
**   r => json object returned from ajax call {success: true|false, msg: ..., insert: top|bottom}
**
**   if insert is 'top'|'bottom', r.msg is prepended|appended to target, otherwise target html is replaced
**   if target is a single id, the target html is updated with r.msg
**   if target is an array and r.msg is not an array, the first target is updated with r.msg
**   if target is an array and r.msg is an array, each taeget is updated with corresponding r.msg element (if it exists)
**   if target is the word "export" then location.href is set to 'action?data'
**   if target is the word "popup" then window.open(action?data... is called
**   if r.redirect then location.href is set to r.redirect
**
**   if r.success is false, r.msg is prepended to target (or target[0] if target is an array)
**
**   (optional) r.close will trigger $.facebox.close(); on success
**   (optional) r.hide_form will hide the form when finished on success
**
*/
function yUpdate(link,target,data){
    var frm = null;
    var act = arguments[3] ? arguments[3] : $(link).attr('action');
    var ind = arguments[4] ? $('#' + arguments[4]) : $('#' + $(link).attr('indicator'));

    if(link.tagName!="SELECT") link.disabled = true; //if you disable a select its value won't post

    $(ind).show();

    data = joinData(data);

    if(target == 'export'){
        location.href = act.concat('?',data)
    } else if(target == 'popup'){
        window.open(act.concat('?',data), 'View', 'width=800,height=500,scrollbars,resizable');
    } else {
        $.ajax({
            type: "POST",
            url: act,
            data: data,
            dataType: "json",
            beforeSend: function(xhr) {xhr.setRequestHeader("Accept", "text/javascript");},
            error:function(xhr, status, errorThrown){
                //alert('{errorThrown: '+errorThrown+', status: '+status+', statusText: '+xhr.statusText);
                alert('An error has occurred in the javascript on this page');
            },
            success: function(r){
                if(r.target){ target = r.target; }
                if(r.success){
                    if(r.redirect){
                        location.href = r.redirect;
                        return;
                    }
                    /* make sure both target and r.msg are arrays */
                    if(!(isArray(target))){ target = [target]; }
                    if(!(isArray(r.msg)) ){ r.msg  = [r.msg];  }

                    removeEditor();

                    /* loop through targets and replace or append/prepend msgs */
                    for(x=0;x<target.length;x++){
                        if(!(r.msg[x] === undefined)){
                            /* insert msg or replace ? */
                            if(r.insert){
                                var hid = $('<div style="display:none;">');
                                switch(r.insert){
                                    case 'bottom': $(hid).html(r.msg[x]).appendTo($('#' + target[x])).show('fast') ; break;
                                    default      : $(hid).html(r.msg[x]).prependTo($('#' + target[x])).show('fast'); break;
                                }
                            } else {
                                $('#' + target[x]).html(r.msg[x]);
                            }

                        }
                    }
                    if(r.close){ $.facebox.close(); }
                    if(r.hide_form && !(frm == null)){ $(frm).hide(); }
                } else {
                    if(isArray(target)){ target = target[0]; }
                    removeEditor();
                    $('#' + target).html(r.msg);
                }
            },
    //        error: function (XMLHttpRequest, textStatus, errorThrown) {
    //            alert(errorThrown);
    //        },
            complete: function(){
                $(link).removeAttr('disabled');
                $(ind).hide();
                formEffects();
                tableEffects();
            }
        });
    }

}

/*
** function yDelete(link,target,data) [... action,ind)]
** Calls action and then removes element or redirects
** yDelete works like exactly yUpdate (above)
**  with the following exceptions:
**
** If r.success == true
**  (optional) r.target will override original target
**  (optional) r.redirect, location.href is set to the value of r.redirect
**  (optional) r.remove, target is removed
**  default: the target element is hidden
**
** If r.success == false,
**  'alert(r.msg);' is called
**
** The link is not re-enabled after a successful call
*/
function yDelete(link,target,data){
    var act = arguments[3] ? arguments[3] : $(link).attr('action');
    var ind = arguments[4] ? $('#' + arguments[4]) : $('#' + $(link).attr('indicator'));

    link.disabled = true;
    $(ind).fadeIn('slow');

    // custom 'name' for confirm?
    var name = 'this item'
    if(typeof data === 'object'){
        if(data.name) name = data.name;
    }

    data = joinData(data);

    if (confirm('Are you sure you want to delete '+name+'?')){
        $.ajax({
            type: "POST",
            url: act,
            data: data,
            dataType: "json",
            beforeSend: function(xhr) {xhr.setRequestHeader("Accept", "text/javascript");},
            success: function(r){
                if(r.target){ target = r.target };
                if(r.success){
                    if(r.redirect){
                        location.href = r.redirect;
                    } else {
                        if(r.msg){
                            $('#' + target).html(r.msg);
                        } else {
                            r.remove ? $('#' + target).remove() : $('#' + target).hide('fast');
                        }
                    }
                } else {
                    alert(r.msg);
                }
            },
            complete: function(){
                $(ind).fadeOut('slow');
            }
        });

    } else {
        $(link).removeAttr('disabled');
        $(ind).fadeOut('slow');
    }
}

/*
** function htmlPopup(url) [,name,data)]
**   url  => controller action to be called
**   name => new window name (optional)
**           defaults to 'New Window' if no name is given
**   data => json data in the form of {width: 400, height: 300, menubar: false, ...} (optional)
**           takes the following keys:
**             <width>(default 800), <height>(default 500)
**             and <scrollbars>, <menubar>, <resizable> (all default true)
*/
function htmlPopup(url){
    var nam  = arguments[1] ? arguments[1] : 'New Window';
    var data = arguments[2] ? arguments[2] : {};

    var features = '';
    features += 'width=' + (data.width || '800');
    features += ',height=' + (data.height || '500');
    if(data.scrollbars!=false) features += ',scrollbars';
    if(data.menubar!=false) features += ',menubar';
    if(data.resizable!=false) features += ',resizable';

    window.open(url, nam, features);

    return false;
}

/*
** Opens a confirmation popup for more actions
**   link => reference to link calling the function (Note: always "this")
**   url  => controller action to be called on confirmation
**   uid  => ytable uid (used to find more_actions form)
*/
function moreActions(link,url,uid){
  link.disabled = true;

  var form = $('#' + uid + '_more_actions');
  var data = form ? $(form).serialize() : {};

  $('#' + uid + '_ma_indicator').show();

  $.ajax({
        type: "POST",
        url: url,
        data: data,
        beforeSend: function(xhr) {xhr.setRequestHeader("Accept", "text/javascript");},
        success: function(msg){
          $.facebox(msg,'inline');
        },
        complete: function(){
          $('#' + uid + '_ma_indicator').hide();
          $(link).removeAttr('disabled');
          formEffects();
        }
    });
}

/*
** Determine if a javascript object is an array
** returns true|false
*/
function isArray(v) {
    return v && typeof v === 'object' && typeof v.length === 'number' && !(v.propertyIsEnumerable('length'));
}

/*
** Serialize form data and combine with json data
** If data is a json object and has an element {form: ...},
** then serialize the form (or forms) and add it to the other elements.
** Note: data overrides form inputs
*/
function joinData(data) {
    if(typeof data === 'object'){
        if(data.form){
            var frm_data = []
            var frms = isArray(data.form) ? data.form : [data.form];

            /* loop throught forms (or form) and get serialized data */
            for(x=0;x<frms.length;x++){
                var f = $('#' + frms[x]);
                if($(f).is('form')){ frm_data[x] = $(f).serialize(); }
            }

            /* combine form_data with other data */
            frm_data = frm_data.join('&');
            if(frm_data.length > 0){
                $.each(data, function(i, val) { if(!(i=='form')){frm_data = frm_data.concat('&',i,'=',val)} } );
                data = frm_data
            }
        }
    }
    return data
}

/*
** Replacement for $.facebox
** relies on JQuery Tools overlay (flowplayer.org)
** It ain't pretty ...
*/
function facebox(msg){
    // get rid of any old one
    $("#facebox").remove();

    // if a class was passed in add it to .content
    var klass = arguments[1] ? 'content ' + arguments[1] : 'content';

    // assemble html
    var popup = '\
  <div id="facebox" style="display:none;"> \
    <div class="popup"> \
      <table> \
        <tbody> \
          <tr> \
            <td class="tl"/><td class="t"/><td class="tr"><a class="close popup-close"/></td> \
          </tr> \
          <tr> \
            <td class="l"/> \
            <td class="body"> \
              <div id="popup_content" class="' + klass + '"> \
              ' + msg + ' \
              </div> \
            </td> \
            <td class="r"/> \
          </tr> \
          <tr> \
            <td class="bl"/><td class="b"/><td class="br"/> \
          </tr> \
        </tbody> \
      </table> \
    </div> \
  </div>';

    // stick it in the bottom of <body>
    $('body').append(popup);

    // call overlay
    $("#facebox").overlay({
	    mask: {color: '#fff',loadSpeed: 200,opacity: 0.5},
	    closeOnClick: false,
        load: true
    });

    return true;
}

/*
** overrides the default facebox close action
** binds yUpdate(this, tar, dat, acn, ind) to close click
*/
function overridePopupClose(tar,acn,dat,ind){
    $('#facebox .popup-close').unbind("click");
    $('#facebox .popup-close').bind("click", function(){
       $.facebox.close();
       yUpdate(this, tar, dat, acn, ind);
       restorePopupClose();
    });
}

/*
** restores the default facebox close action
*/
function restorePopupClose(){
    $('#facebox .popup-close').unbind("click");
    $('#facebox .popup-close').bind("click",$.facebox.close);
}

/*
** assures that a valid date format (mm/dd/yyyy) has been entered in an input
** usage => onblur="validateDate(this);"
*/
function validateDate(i){
	var m = null; var d = null; var y = null;
	var formatted = null;
	var str = i.value;

        if(str.length < 3){ return }

        var now   = /^\s*(now|today)/i;
        var match = now.exec(str);
        if(match){
            d = new Date();
            i.value = (d.getMonth() + 1) + '/' + d.getDate() + '/' + d.getFullYear();
            return
        }
/*
        var reg1 = /^(\d{1,2})[\.\-\/](\d{1,2})[\.\-\/](\d{4})$/;		// = mm/dd/yyyy
	var reg2 = /^(\d{1,2})[\.\-\/](\d{1,2})[\.\-\/](\d{1,2})$/;		// = mm/dd/yy or m/d/y
	var reg3 = /^(\d{1,2})[\.\-\/](\d{1,2})$/;						// = mm/dd or m/d

        var match = reg1.exec(str);	// = mm/dd/yyyy
	if(match){
		m = parseInt(match[1],10);
		d = parseInt(match[2],10);
		y = parseInt(match[3],10);
	} else {
		match = reg2.exec(str); // = mm/dd/yy or m/d/y
		if(match){
			m = parseInt(match[1],10);
			d = parseInt(match[2],10);
			y = parseInt(match[3],10);
			y = y < 30 ? 2000 + y : 1900 + y;
		} else {
			match = reg3.exec(str); // = mm/dd or m/d
			if(match){
				m = parseInt(match[1],10);
				d = parseInt(match[2],10);
				y = new Date();
				y = y.getFullYear();
			}
		}
	}

	if(m==2){
		var maxDay = ((y % 4 == 0) && ((y % 100 != 0) || (y % 400 == 0))) ? 29 : 28;
		if(d <= maxDay && d > 0){
			formatted = m + '/' + d + '/' + y;
		}
	} else {
		var maxDays = [31,28,31,30,31,30,31,31,30,31,30,31];
		if(maxDays[m-1] != null && d <= maxDays[m-1] && d > 0){
			formatted = m + '/' + d + '/' + y;
		}
	}

	if(formatted){
		i.value = formatted;
	} else {
		i.value = '';
		alert('"' + str + '" is not a valid date!');
	}
*/
}
function formatTime(i){
	var reg = /^(2[0-4]|1[0-9]|[0-9]){1}\:*([0-5][0-9])*\s*((\.|a|p)m*)*$/i;
	var s = i.value;
	var d = reg.exec(s);
	if(d){
		//alert(d[1] + " : " + d[2] + " : " + d[3] + " : " + d[4]);
		mn = (d[4] == 'p' || d[4] == '.') ? ' PM' : ' AM';
		m  = d[2] ? Math.round(parseInt(d[2],10)/15) * 15 : 0;
		h  = d[1] == '0' ? 12 : parseInt(d[1]);
		if(m==60){
			m = 0;
			h = h + 1;
			if(h==12){
				mn = mn == ' PM' ? ' AM' : ' PM'
			}
		}
		if(h>12){
			h  = parseInt(h) - 12;
			m  = h == 12 ? '00' : m;
			mn = h == 12 ? ' AM' : ' PM'
		}
		m  = m < 10 ? '0' + m : m;
		i.value = h + ":" + m + mn;
	} else {
		i.value="";
		alert("'" + s + "' is not a valid time format!'");
	}
}

/* Simple function to show /hide a given tab based on the
tabs that are drawn by the form helper */
function showTab(tabname){
    var tab = "#" + "tab_" + tabname;               // i.e. tab_jobs
    var content = "#" + tabname + "_tab";           // i.e. jobs_tab

    $(".tab").removeClass('active');
    $(".tab-content").hide();
    $(tab).addClass('active');
    $(content).show();
}

/* Loads a tab using ajax if it is not already loaded. Uses
naming conventions specific to the draw_on_demand_tab function */
function loadTab(tabname){
    var tab = "#" + "tab_" + tabname;               // i.e. tab_jobs
    var content = "#" + tabname + "_tab";           // i.e. jobs_tab

    $(".tab").removeClass('active');
    $(".tab-content").hide();


    if($(tab).hasClass('loaded')){
      // just show it
      $(tab).addClass('active');
      $(content).show();
    } else {
      // load it via ajax
      $('#' + tabname + '_indicator').show();

      $.ajax({
            type: "POST",
            url: "/admin/load_tab_" + tabname,
            data: "",
            beforeSend: function(xhr) {xhr.setRequestHeader("Accept", "text/javascript");},
            success: function(r){
              $(content).html(r);
            },
            complete: function(){
              $('#' + tabname + '_indicator').hide();
              $(tab).addClass('active');
              $(tab).addClass('loaded');
              $(content).show();
              formEffects();
              tableEffects();
            }
        });
    }

}


/*
** onload functionality for the universal search input

$(function(){
  $('#universal_search').focus(function(){
      $(this).css({border: '2px solid #999', background: '#fff'});
      if($(this).val()=='Search...'){$(this).val('');}
      });
  $('#universal_search').blur(function(){
        $(this).css({border: '1px solid #aaa', background: '#eee'});
        if($(this).val()==''){$(this).val('Search...');}
      });
});*/
//$(function(){
//  $('#universal_search').focus(function(){
//      $(this).css({backgroundColor: '#ffd'});
//      });
//  $('#universal_search').blur(function(){
//        $(this).css({backgroundColor: '#fff'});
//      });
//  $("#universal_search").autocomplete("/home/autocomplete_names", {
//          minChars: 1,
//          width: 250,
//          matchContains: true,
//          formatItem: function(row, i, max) {
//                  var m = row[2] == 'applicants' ? 'Applicant' : row[2] == 'pools' ? 'Pool' : 'Job'
//                  return row[0] + " (" + m + ":" + row[1] + ")";
//          },
//          formatResult: function(row) {
//                  return row[0];
//          }
//  });
//  $("#universal_search").result(function(event, data, formatted) {
//          location.href = "/" + data[2] + "/show/" + data[1] + "/";
//          //this.form.submit();
//  });
//});
function refresh(){ location.reload(true); }

/* Function to show docunemt upload form in a popup */
function showUploadForm(id){
    var ie6 = $.browser.msie && /MSIE 6.0/.test(navigator.userAgent);
    var form = $('#new_document_' + id);
    if(!ie6){ $('#content').block(); }
    $.facebox(form);
}

function ratingClick(size,rating){
    var stars = arguments[2] ? document.getElementById(arguments[2] + '_stars') : document.getElementById('stars');
    var rate = arguments[2] ? document.getElementById(arguments[2] + '_rating') : document.getElementById('rating');
    var width = size == 'big' ? 30 : size == 'medium' ? 23 : 11
    stars.style.width = (rating * width) + 'px';
    rate.value = rating;
}
/*
** Posts to /share/ with event and share and returns true
**   event<Integer> => event.id
**   share<String>  => name of network ('facebook', 'twitter', etc.)
*/
function eventShare(event,share){
  $.post('/share/' + event, {share: share});
  return true;
}

// Better Toggle functions
(function($) {
	$.fn.toggleSlideFade = function(settings)
	{
		if(settings==undefined) {
			settings={ speedIn : 'slow'};
		}

		settings = jQuery.extend(
				{
					speedIn: "normal",
					speedOut: settings.speedIn
				}, settings
		);
		return this.each(function()
				{
			var isHidden = jQuery(this).is(":hidden");
			jQuery(this)[ isHidden ? "fadeIn" : "fadeOut" ]( isHidden ? settings.speedIn : settings.speedOut);
				});
	};
})(jQuery);

(function($) {
	$.fn.toggleSlide = function(settings)
	{
		if(settings==undefined) {
			settings={ speedIn : 'slow'};
		}

		settings = jQuery.extend(
				{
					speedIn: "normal",
					speedOut: settings.speedIn
				}, settings
		);
		return this.each(function()
				{
			var isHidden = jQuery(this).is(":hidden");
			jQuery(this)[ isHidden ? "slideDown" : "slideUp" ]( isHidden ? settings.speedIn : settings.speedOut);
				});
	};
  })(jQuery);

function ltdLoadInitial(market) {
  if(market == null) { var market = ''; }

  $.ajax({
      type: "POST",
      url: '/main/load_ltd/' + market,
      data: {widget: 'ltd'},
      beforeSend: function(xhr) {xhr.setRequestHeader("Accept", "text/javascript");},
      success: function(msg){
        $('#ltd-widget').html(msg);
      },
      complete: function(){
        if($('.ltd-frame').size() > 3) ltdRefresh(5);
        $('#ltd-spinner').hide();
      }
  });
}

function cbsLoadInitial(market) {
  if(market == null) { var market = ''; }

  $.ajax({
      type: "POST",
      url: '/main/load_cbs/' + market,
      data: {widget: 'cbs'},
      beforeSend: function(xhr) {xhr.setRequestHeader("Accept", "text/javascript");},
      success: function(msg){
        $('#cbs-widget').html(msg);
      },
      complete: function(){
        if($('.cbs-frame').size() > 3) cbsRefresh(5);
        $('#cbs-spinner').hide();
      }
  });
}

function rfyLoadInitial(market) {
  if(market == null) { var market = ''; }

  $.ajax({
      type: "POST",
      url: '/main/load_rfy/' + market,
      data: {widget: 'rfy'},
      beforeSend: function(xhr) {xhr.setRequestHeader("Accept", "text/javascript");},
      success: function(msg){
        $('#rfy-widget').html(msg);
        $('#rfy-widget').toggleSlideFade(1000);
      },
      complete: function(){
        $('#rfy-spinner').hide();
      }
  });
}

function ltdRefresh() {
  base = arguments[0] ? arguments[0] : 10;
  var delay = ((Math.floor(Math.random()*10))+base)*1000;
  setTimeout("ltdScroll()", delay);
}

function ltdScroll() {
  var firstFrame = $('.ltd-frame:first');
  var lastFrame = $('.ltd-frame:last');
  var nextFrame = $('.ltd-frame:hidden:last');
  $(nextFrame).toggleSlide('slow');
  $(lastFrame).hide().insertBefore(firstFrame);
  ltdRefresh();
}

function cbsRefresh() {
  base = arguments[0] ? arguments[0] : 10;
  var delay = ((Math.floor(Math.random()*10))+base)*1000;
  setTimeout("cbsScroll()", delay);
}

function cbsScroll() {
  var firstFrame = $('.cbs-frame:first');
  var lastFrame = $('.cbs-frame:last');
  var nextFrame = $('.cbs-frame:hidden:last');
  $(nextFrame).toggleSlide('slow');
  $(lastFrame).hide().insertBefore(firstFrame);
  cbsRefresh();
}


