// HUY NGUYEN
// Common javascript used throughout the website

    /* Overloading string to include trim functions */
    /*
    String.prototype.trim  = function() { return this.replace(/^\s+|\s+$/g,""); }
    String.prototype.ltrim = function() { return this.replace(/^\s+/,""); }
    String.prototype.rtrim = function() { return this.replace(/\s+$/,""); }
    */


  $j = jQuery.noConflict();
  $ = jQuery;

  var myWindow;
  function openCenteredWindow(url, width, height) {
      var left = parseInt((screen.availWidth/2) - (width/2));
      var top = parseInt((screen.availHeight/2) - (height/2));
      var windowFeatures = "width=" + width + ",height=" + height + ",status,resizable,left=" + left + ",top=" + top + "screenX=" + left + ",screenY=" + top;
      myWindow = window.open(url, "subWind", windowFeatures);
  }

  function addCommas(nStr) {
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
      x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
  }

  // Removes [$,] AND .00
  function remove_format(value) {
    value = value.replace(/[\$]/, '');
    value = value.replace(/[,]/, '');
    value = value.replace(/[.]+[0-9]*/, '');

    return value;
  }

  // Add $ AND , AND .00 (SIMPLIFY VERSION)
  function format_money_simple(value) {
    value = remove_format(value);
    value = '$' + addCommas(value) + '.00'; 

    return value;
  }

  // Add $ AND , AND .00
  function format_money(element) {
    value = element.value;
    value = remove_format(value);

    element.value = addCommas(value) + '.00'; 

    get_total();
    return false;
  }

  // generate total values for each row
  function get_total() {
    $j(".total").each(function() {
      var expense = $j(this).parent().prev().prev().prev().children("input").val();
      var spouse  = $j(this).parent().prev().prev().children("input").val();
      var child   = $j(this).parent().prev().children("input").val();

      expense = remove_format(expense);
      spouse  = remove_format(spouse);
      child   = remove_format(child);

      expense = (expense == '') ? 0 : parseInt(expense);
      spouse  = (spouse == '')  ? 0 : parseInt(spouse);
      child   = (child == '')   ? 0 : parseInt(child);

      var total = expense + spouse + child;

      $j(this).val(format_money_simple(total.toString()));
    });
  }


  // validate email
  function checkEmail(email) {
    var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    if (!filter.test(email)) {
      return false;
    }
    return true;
  }

  // alert invalid email 
  function validate_email(form, field, name) {
    var email  = document.forms[form][field].value;
    if (!checkEmail(email)) {
      alert("Please input a valid email address for: " + name);
      return false;
    }
    return true;
  }

  $j(function() {
    $j(".switch_src_alt").hover(function() {
      var alt = $j(this).attr('alt');
      var src = $j(this).attr('src');

      $j(this).attr('alt', src);
      $j(this).attr('src', alt);
    }, function() {
      alt = $j(this).attr('alt');
      src = $j(this).attr('src');

      $j(this).attr('alt', src);
      $j(this).attr('src', alt);
    });
  });


  /* TRIM FUNCTIONS: start (magic method / overloading) */
  String.prototype.trim = function()  { return this.replace(/^\s+|\s+$/g,""); }
  String.prototype.ltrim = function() { return this.replace(/^\s+/,""); }
  String.prototype.rtrim = function() { return this.replace(/\s+$/,""); }
  /* TRIM FUNCTIONS: end */


  /* Clear default form field when user focuses on input */
  function clearField(field) {
    if (field.defaultValue == field.value) field.value = ""
  }

  /* Fill in form with default value if nothing was entered */
  function fillField(field) {
    var entered_value = field.value;
    if (entered_value.trim() == '') field.value = field.defaultValue;
  }


  /* Makes sure keyword field is not filled with a bunch of white spaces before submitting form */
  function check_keyword(form_name, field_check) {
    var form  = document.forms[form_name];
    var field = form[field_check].value;

    if (field.trim() != '')
      return form.submit();

    alert('Please type a keyword to begin search.');
  }


  // TEXT COUNTER CODE
  function textCounter(field,cntfield,maxlimit) {
  if (field.value.length > maxlimit) // if too long...trim it!
  field.value = field.value.substring(0, maxlimit);
  // otherwise, update 'characters left' counter
  else
  cntfield.value = maxlimit - field.value.length;
  }

  function update_length(form, field, counter, max) {
    var form            = document.forms[form];
    var current_length  = form[field].value.length;
    form[counter].value = max - current_length;
  }



/**********
* Gallery Slideshow
**********/
// custom fadeToggle
$j.fn.fadeToggle = function(speed,easing,callback) {
	return this.animate({opacity: 'toggle'}, speed, easing, callback);
};


function getSlideWidth(ratio,maxW,maxH) {
	var minRatio = maxW / maxH;
	var width;
	var height;
	if(ratio <= minRatio) {
	  width = maxH * ratio;
	  height = maxH;
	}
	else {
	  width = maxW;
	  height = maxW / ratio;
	}
	
	return new Array(width,height);
}


function slideshow() {
	
	// get current img
	var current = $j('.gallery .slides a');
	
	// get thumbs
	var thumbs = $j('.gallery .thumbs a');
	
	var first = $j(thumbs[0]);
	var prev = $j(current[0]).clone(true);
	var prevImg = prev.children('img');
	var next = first.clone(true);
	var nextImg = next.children('img');
	current.fadeOut('slow',function() {
		current.remove();
	});
	// handle dimensions
	var nextW = nextImg.css('width').slice(0,-2);
	var nextH = nextImg.css('height').slice(0,-2);
	var newSize = getSlideWidth(nextW/nextH,204,165);
	next.children('img').css({'width': newSize[0]+'px', 'height': newSize[1]+'px'});
	var prevW = prevImg.css('width').slice(0,-2);
	var prevH = prevImg.css('height').slice(0,-2);
	newSize = getSlideWidth(prevW/prevH,65,65);
	prevImg.css({'width': newSize[0]+'px', 'height': newSize[1]+'px'});
	
	next.hide();
	next.insertAfter(current);
	next.fadeIn('slow');
	
	first.hide('slide',function() {
		first.remove();
		prev.insertAfter('.gallery .thumbs a:last');
	});
	
	timer = setTimeout(slideshow,10000);
}


var timer;

$j(function() {
	if($j('.gallery img').length>1)
		timer = setTimeout(slideshow,5000);
});
