$(document).ready(function(){
  $('#container').flash({
    'src': '/system/flash/swf/index.swf',
    'width': '100%',
    'height': '100%',
    'allowfullscreen': 'false',
    'allowscriptaccess': 'always',
    'bgcolor': '#000000',
    'id': 'sherlocks'
  });

  populate_states();

  default_location_html = $('#location').html();

  $("#state").bind("change", function() {
    var state = $(this).val();
    if (state == "") {
      return;
    }
    populate_cities(state);
  });

  $("#city").bind("change", function() {
    var state = $('#state').val();
    var city = $(this).val();
    if (city == "") {
      return;
    }
    populate_locations(state, city);
  });

  $("#location").bind("change", function() {
    var location = $(this).val().split(",", 2);
    movieObj('sherlocks').launchLocation(location);
  });

  $("#zipcode_search").bind("submit", function() {
    var zipcode = $("#zipcode").val();
    locations_for_zipcode(zipcode);
    return false;
  });

/*======================================================================== WATERMARK FUNCTION
DEPENDS ON: jQuery
USE:    Add class to any input form needing a watermark. Title must be set also.*/
  if ($('.defaultText').length) {
    $('.defaultText').focus(function () {
      if ($(this).val() == $(this).attr("title")) {
        $(this).val("");
      }
    }).blur(function () {
      if ($(this).val() == "") {
        $(this).val($(this).attr("title"));
      }
    });
  };
});

function hide_locator() {
  $('.locator').hide();
}

function show_locator() {
  $('.locator').show();
}

function populate_states() {
  $.ajax({
    data:jQuery.param(jQuery(this).serializeArray()),
    type:'post',
    dataType:'script',
    url:'/locations/states'});
}

function populate_cities(state) {
  $.ajax({
    data:"state=" + state,
    type:'post',
    dataType:'script',
    url:'/locations/state_cities'});

  clear_city_locations();
}

function populate_locations(state, city) {
  $.ajax({
    data:"state=" + state + "&city=" + city,
    type:'post',
    dataType:'script',
    url:'/locations/city_locations'});
}

function locations_for_zipcode(zipcode) {
  $.post('/locations/near_zipcode', { 'zipcode': zipcode },
      function(data) { movieObj('sherlocks').showLocationResults(eval(data)) });
}

// function locations_for_zipcode(zipcode) {
//   $.ajax({
//     data:"zipcode=" + zipcode,
//     type:'post',
//     dataType:'script',
//     url:'/locations/near_zipcode',
//     success: function(data) { alert(data) }});
//     // success: function(data) { movieObj('sherlocks').showLocationResults(JSON.parse(data)) }});
// }


function clear_city_locations() {
  $('#location').html(default_location_html);
}


function movieObj(movieName) {
  if (window.document[movieName]) {
    return window.document[movieName];
  }

  if (navigator.appName.indexOf("Microsoft Internet")==-1) {
    if (document.embeds && document.embeds[movieName]) {
      return document.embeds[movieName];
    }
  } else if (navigator.appName.indexOf("Microsoft Internet")!=-1) {
    return document.getElementById(movieName);
  }
}


function submitContactForm(data) {
  for (var key in data) {
    var id = '#customer_comment_' + key;
    value = data[key];
    if (data[key] == 0 || data[key] == "") {
      value = null;
    }

    $(id).val(data[key]);
  }

  document.forms[2].onsubmit();
}



function add_employment_checkbox(name, num) {
  id = 'employment_application_' + name + '_' + num;
  var form_container = document.getElementById('new_employment_application');
  var cb = document.createElement('input');
  cb.type = 'checkbox';
  cb.name = "employment_application[" + name + "][]";
  cb.value = num;
  cb.id = id;
  cb.checked = "checked";
  form_container.appendChild(cb);
}



function clear_existing_checkboxes() {
  for (var i = 1; i <= 7; i++) {
    am = $('#employment_application_am_availabilities_' + i);
    pm = $('#employment_application_pm_availabilities_' + i);
    if (am) {
      am.remove();
    }
    if (pm) {
      pm.remove();
    }
  }
}



function submitEmploymentForm(data) {
  clear_existing_checkboxes();

  for (var key in data) {
    value = data[key];
    if (num = key.match(/work_am_(\d)/)) {
      if (value) {
        add_employment_checkbox('am_availabilities', parseInt(num[1], 10) + 1);
      }
    } else if (num = key.match(/work_pm_(\d)/)) {
      if (value) {
        add_employment_checkbox('pm_availabilities', parseInt(num[1], 10) + 1);
      }
    } else {
      id = '#employment_application_' + key;
      if (value == 0 || value == "") {
        value = null;
      }
      $(id).val(value);
    }
  }

  document.forms[3].onsubmit();
}

/**
 * jquery.dump.js
 * @author Torkild Dyvik Olsen
 * @version 1.0
 *
 * A simple debug function to gather information about an object.
 * Returns a nested tree with information.
 *
 */
(function($) {
  $.fn.dump = function() {
    return $.dump(this);
  }

  $.dump = function(object) {
    var recursion = function(obj, level) {
      if (!level) level = 0;
      var dump = '',
        p = '';
      for (i = 0; i < level; i++) p += "\t";

      t = type(obj);
      switch (t) {
      case "string":
        return '"' + obj + '"';
        break;
      case "number":
        return obj.toString();
        break;
      case "boolean":
        return obj ? 'true' : 'false';
      case "date":
        return "Date: " + obj.toLocaleString();
      case "array":
        dump += 'Array ( \n';
        $.each(obj, function(k, v) {
          dump += p + '\t' + k + ' => ' + recursion(v, level + 1) + '\n';
        });
        dump += p + ')';
        break;
      case "object":
        dump += 'Object { \n';
        $.each(obj, function(k, v) {
          dump += p + '\t' + k + ': ' + recursion(v, level + 1) + '\n';
        });
        dump += p + '}';
        break;
      case "jquery":
        dump += 'jQuery Object { \n';
        $.each(obj, function(k, v) {
          dump += p + '\t' + k + ' = ' + recursion(v, level + 1) + '\n';
        });
        dump += p + '}';
        break;
      case "regexp":
        return "RegExp: " + obj.toString();
      case "error":
        return obj.toString();
      case "document":
      case "domelement":
        dump += 'DOMElement [ \n' + p + '\tnodeName: ' + obj.nodeName + '\n' + p + '\tnodeValue: ' + obj.nodeValue + '\n' + p + '\tinnerHTML: [ \n';
        $.each(obj.childNodes, function(k, v) {
          if (k < 1) var r = 0;
          if (type(v) == "string") {
            if (v.textContent.match(/[^\s]/)) {
              dump += p + '\t\t' + (k - (r || 0)) + ' = String: ' + trim(v.textContent) + '\n';
            } else {
              r--;
            }
          } else {
            dump += p + '\t\t' + (k - (r || 0)) + ' = ' + recursion(v, level + 2) + '\n';
          }
        });
        dump += p + '\t]\n' + p + ']';
        break;
      case "function":
        var match = obj.toString().match(/^(.*)\(([^\)]*)\)/im);
        match[1] = trim(match[1].replace(new RegExp("[\\s]+", "g"), " "));
        match[2] = trim(match[2].replace(new RegExp("[\\s]+", "g"), " "));
        return match[1] + "(" + match[2] + ")";
      case "window":
      default:
        dump += 'N/A: ' + t;
        break;
      }

      return dump;
    }

    var type = function(obj) {
      var type = typeof(obj);

      if (type != "object") {
        return type;
      }

      switch (obj) {
      case null:
        return 'null';
      case window:
        return 'window';
      case document:
        return 'document';
      case window.event:
        return 'event';
      default:
        break;
      }

      if (obj.jquery) {
        return 'jquery';
      }

      switch (obj.constructor) {
      case Array:
        return 'array';
      case Boolean:
        return 'boolean';
      case Date:
        return 'date';
      case Object:
        return 'object';
      case RegExp:
        return 'regexp';
      case ReferenceError:
      case Error:
        return 'error';
      case null:
      default:
        break;
      }

      switch (obj.nodeType) {
      case 1:
        return 'domelement';
      case 3:
        return 'string';
      case null:
      default:
        break;
      }

      return 'Unknown';
    }

    return recursion(object);
  }



  function trim(str) {
    return ltrim(rtrim(str));
  }



  function ltrim(str) {
    return str.replace(new RegExp("^[\\s]+", "g"), "");
  }



  function rtrim(str) {
    return str.replace(new RegExp("[\\s]+$", "g"), "");
  }
})(jQuery);

function getWindowHeight() {
	var windowHeight = 0;
	if (typeof(window.innerHeight) == 'number') {
		windowHeight = window.innerHeight;
	}
	else {
		if (document.documentElement && document.documentElement.clientHeight) {
			windowHeight = document.documentElement.clientHeight;
		}
		else {
			if (document.body && document.body.clientHeight) {
				windowHeight = document.body.clientHeight;
			}
		}
	}
	return windowHeight;
}

function setContent() {
	if (document.getElementById) {
		var windowHeight = getWindowHeight();
		if (windowHeight > 0) {
			var contentElement = document.getElementById('content');
			var contentHeight = contentElement.offsetHeight;
			if (windowHeight - contentHeight > 0) {
				contentElement.style.position = 'relative';
				contentElement.style.top = ((windowHeight / 2) - (contentHeight / 2)) + 'px';
			}
			else {
				contentElement.style.position = 'static';
			}
		}
	}
}

window.onload = function() {
	setContent();
}
window.onresize = function() {
	setContent();
}

