
$(document).ready(function() {
  //scroll the message box to the top offset of browser's scrool bar
  $(window).scroll(function() {
     $('#message_box').animate({top:$(window).scrollTop()+"px" },{queue: false, duration: 350});  
  });
  
  //when the close button at right corner of the message box is clicked 
  $('#close_message').click(function() {
    $('#message_box').hide();
  });

  if ($.util.getQueryParam('message')) {
    $.util.printMessage($.util.getQueryParam('message'));
  }

});

$.cache = {};

$.util = {

  colors: {
    'red'    : '#E7283B',
    'yellow' : '#FFE07B',
    'green'  : '#BAD47F',
    'blue'   : '#d7f2f8'
  },

  currency: function(number) {
    return '$' + number.toFixed(2);
  },

  getQueryParam: function( parameterName ) {
    var queryString = window.top.location.search.substring(1)
    // Add "=" to the parameter name (i.e. parameterName=value)
    var parameterName = parameterName + "=";
    if ( queryString.length > 0 ) {
      // Find the beginning of the string
      begin = queryString.indexOf ( parameterName );
      // If the parameter name is not found, skip it, otherwise return the value
      if ( begin != -1 ) {
        // Add the length (integer) to the beginning
        begin += parameterName.length;
        // Multiple parameters are separated by the "&" sign
        end = queryString.indexOf ( "&" , begin );
        if ( end == -1 ) {
          end = queryString.length
        }
        // Return the string
        return unescape ( queryString.substring ( begin, end ) );
      }
      // Return "null" if no parameter has been found
    }
  },

  highlightInput: function(input) {
    $('#'+input).addClass('input-error');
    $('textarea#'+input).addClass('input-error');
  },

  post: function(url, data, callback, addl) {
    var request = {
      cache: false,
      error: function (XMLHttpRequest, textStatus, errorThrown) {
        $.util.printError(textStatus+":  "+errorThrown);
      },
      url: url,
      type: 'post',
      data: data,
      dataType: 'json',
      success: function(data, txtStatus) {
        if (data.error) {
	  $.util.printError(data.error);
          $('.form-button').show();
	  $('.throbber').hide();
        } else {
          $('.form-button').show();
	  $('.throbber').hide();
          $.util.clearError();
          callback(data.data);
        }
      }
    };
    // any additional $.ajax parameters
    for(key in addl) {
      request[key] = addl[key];
    }
    $.ajax(request); 
  },

  submit: function(selector, url, data, callback, addl) {
    var request = {
      cache: false,
      error: function (XMLHttpRequest, textStatus, errorThrown) {
        $.util.printError(textStatus+":  "+errorThrown);
      },
      url: url,
      type: 'post',
      data: data,
      dataType: 'json',
      success: function(data, txtStatus) {
        if (data.error) {
          $.util.printError(data.error);
        } else {
          $.util.clearError();
          callback(data.data);
        }
      }
    };
    // any additional $.ajax parameters
    for(key in addl) {
      request[key] = addl[key];
    }
    $(selector).ajaxSubmit(request);    
  },

  printError: function(error) {
    var arrErrors = Array();
    if (typeof(error) == 'object' && error != null) {
      if ('missing' in error && error.missing != null) {
        // clear all highlighted inputs
        $(':input').removeClass('input-error');
        arrErrors.push('Required fields are highlighted in red');
        for (field in error.missing) {
          $.util.highlightInput(field);
        }
      } else if ('invalid' in error && error.invalid != null) {
	$(':input').removeClass('input-error');
	for (field in error.invalid) {
	  $.util.highlightInput(field);
	  arrErrors.push(error.invalid[field]);
	}
      } else { // assume array?
        arrErrors = error;
      }
    } else {
      arrErrors.push(error);
    }
    
    if ($('#modal-container :visible').length > 0) { // we have a modal present, so present errors there
      var modalMessageBox = $('#modal_message_box');
      modalMessageBox.hide();
      modalMessageBox.children('#modal_message').html(arrErrors.join('<br>'));
      modalMessageBox.css({'backgroundColor':$.util.colors.yellow});
      modalMessageBox.fadeIn('normal');
    } else if ($('#message_box').length > 0) { // regular (non-modal) message box
      var MessageBox = $('#message_box');
      MessageBox.hide();
      MessageBox.children('#message').html(arrErrors.join('<br>'));
      MessageBox.css({'backgroundColor':$.util.colors.yellow});
      MessageBox.css({'color':'#000000'});
      MessageBox.fadeIn('normal');        
      setTimeout(function(){MessageBox.fadeOut('fast');},3000); 
    } else {
      alert(arrErrors.join('<br>'));
    }
  },
  
  printMessage: function(message) {
      var MessageBox = $('#message_box');
      MessageBox.hide();
      MessageBox.children('#message').html(message);
      MessageBox.css({'backgroundColor':$.util.colors.green});
      MessageBox.fadeIn('normal');    
      setTimeout(function(){MessageBox.fadeOut('fast');},2000); 
  },
    
  clearError: function() {
    if($('#message_box').length > 0) { $('#message_box').hide(); }
    if($('#modal_message_box').length > 0) { $('#modal_message_box').hide(); }   
    $(':input').removeClass('input-error');  
  },
  
  modal: function(args) {
  
    var titleHeight = 35;
  
    var width = args.width || 300;
    var height = args.height || 60;
    height += titleHeight;
    
    var url = args.url;
    var onSuccess = args.onSuccess;
    // cache onSuccess for use in modals
    $.cache.onSuccess = onSuccess;
    
    var onFailure = args.onFailure;
    var okayText = (args.okayText) ? args.okayText : 'Okay';
    var cancelText = (args.cancelText) ? args.cancelText : 'Cancel';
    var title = args.title;
    var onLoad = (args.onLoad) ? args.onLoad : function() {};
    var body = args.body;

    var params = args.params || {};
    params.height = height;
    params.width = width;
    var dt = new Date();
    params.cachebuster = dt.getTime(); 

    // instantiate the modal with the full height
    $.modal('<div id="simplemodal-title">Loading...</div>', { 
      minWidth: width+'px', 
      minHeight:height+'px',
      overlayClose:false,
      containerCss: {width: width+'px', height: height+'px' }
    });
    // then resize so just the titlebar shows (while the content loads)
    $('#simplemodal-container').css({height:titleHeight});
    $.get(url, params, function(data) {
      // now resize to the full height
      $('#simplemodal-container').animate({height:height+'px'});
      $('#simplemodal-data').append(data);
      $('#simplemodal-title').html(title);
      if(body !== undefined) {
	$('#modal-main').prepend('<p style="padding:5px">'+body+'</p>');
      }
      // bind the callbacks
      $('a#modal-okay').click(onSuccess);
      $('a#modal-okay').html(okayText);
      $('a#modal-cancel').click(onFailure);
      $('a#modal-cancel').html(cancelText);
      onLoad();
    });
  },

  trackPageview: function(url) {
    // only send pageview to google analytics if ga is loaded 
    if (typeof(pageTracker) != "undefined") {
      pageTracker._trackPageview(url);
    }
  }
}
