﻿// Google Analytics
var icast_mod_gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + icast_mod_gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));


// Language String Variables
var icast_Text_EnterCity;
var icast_Text_Close;
var icast_Text_MultipleMatches;
var icast_Text_SearchNoResults;
var icast_Text_PleaseCheckSpelling;
var icast_Text_LocationSaved;
var icast_Text_UnitedStates;
var icast_Text_ProvideValidEmail;
var icast_Text_PasswordCharLength;
var icast_Text_PasswordAndConfirmationNotMatch;
var icast_Text_SelectForecastLocation;
var icast_Text_AcceptsTermsAndPrivacy;
var icast_Text_ProvideValidUsername;
var icast_Text_SpecifyPassword;
var icast_Text_SpecifyCurrentPassword;
var icast_Text_NewPasswordCharLength;
var icast_Text_NewPasswordAndConfirmationNotMatch;
var icast_Text_VerifyUnsubscribe;


/**********************************
* jQuery Autocomplete plugin 1.1
*
* Copyright (c) 2009 Jörn Zaefferer
*
* Dual licensed under the MIT and GPL licenses:
*   http://www.opensource.org/licenses/mit-license.php
*   http://www.gnu.org/licenses/gpl.html
*
* Revision: $Id: jquery.autocomplete.js 15 2009-08-22 10:30:27Z joern.zaefferer $
*/
; (function ($) {
  $.fn.extend({ autocomplete: function (urlOrData, options) { var isUrl = typeof urlOrData == "string"; options = $.extend({}, $.Autocompleter.defaults, { url: isUrl ? urlOrData : null, data: isUrl ? null : urlOrData, delay: isUrl ? $.Autocompleter.defaults.delay : 10, max: options && !options.scroll ? 10 : 150 }, options); options.highlight = options.highlight || function (value) { return value; }; options.formatMatch = options.formatMatch || options.formatItem; return this.each(function () { new $.Autocompleter(this, options); }); }, result: function (handler) { return this.bind("result", handler); }, search: function (handler) { return this.trigger("search", [handler]); }, flushCache: function () { return this.trigger("flushCache"); }, setOptions: function (options) { return this.trigger("setOptions", [options]); }, unautocomplete: function () { return this.trigger("unautocomplete"); } }); $.Autocompleter = function (input, options) { var KEY = { UP: 38, DOWN: 40, DEL: 46, TAB: 9, RETURN: 13, ESC: 27, COMMA: 188, PAGEUP: 33, PAGEDOWN: 34, BACKSPACE: 8 }; var $input = $(input).attr("autocomplete", "off").addClass(options.inputClass); var timeout; var previousValue = ""; var cache = $.Autocompleter.Cache(options); var hasFocus = 0; var lastKeyPressCode; var config = { mouseDownOnSelect: false }; var select = $.Autocompleter.Select(options, input, selectCurrent, config); var blockSubmit; $.browser.opera && $(input.form).bind("submit.autocomplete", function () { if (blockSubmit) { blockSubmit = false; return false; } }); $input.bind(($.browser.opera ? "keypress" : "keydown") + ".autocomplete", function (event) { hasFocus = 1; lastKeyPressCode = event.keyCode; switch (event.keyCode) { case KEY.UP: event.preventDefault(); if (select.visible()) { select.prev(); } else { onChange(0, true); } break; case KEY.DOWN: event.preventDefault(); if (select.visible()) { select.next(); } else { onChange(0, true); } break; case KEY.PAGEUP: event.preventDefault(); if (select.visible()) { select.pageUp(); } else { onChange(0, true); } break; case KEY.PAGEDOWN: event.preventDefault(); if (select.visible()) { select.pageDown(); } else { onChange(0, true); } break; case options.multiple && $.trim(options.multipleSeparator) == "," && KEY.COMMA: case KEY.TAB: case KEY.RETURN: if (selectCurrent()) { event.preventDefault(); blockSubmit = true; return false; } break; case KEY.ESC: select.hide(); break; default: clearTimeout(timeout); timeout = setTimeout(onChange, options.delay); break; } }).focus(function () { hasFocus++; }).blur(function () { hasFocus = 0; if (!config.mouseDownOnSelect) { hideResults(); } }).click(function () { if (hasFocus++ > 1 && !select.visible()) { onChange(0, true); } }).bind("search", function () { var fn = (arguments.length > 1) ? arguments[1] : null; function findValueCallback(q, data) { var result; if (data && data.length) { for (var i = 0; i < data.length; i++) { if (data[i].result.toLowerCase() == q.toLowerCase()) { result = data[i]; break; } } } if (typeof fn == "function") fn(result); else $input.trigger("result", result && [result.data, result.value]); } $.each(trimWords($input.val()), function (i, value) { request(value, findValueCallback, findValueCallback); }); }).bind("flushCache", function () { cache.flush(); }).bind("setOptions", function () { $.extend(options, arguments[1]); if ("data" in arguments[1]) cache.populate(); }).bind("unautocomplete", function () { select.unbind(); $input.unbind(); $(input.form).unbind(".autocomplete"); }); function selectCurrent() { var selected = select.selected(); if (!selected) return false; var v = selected.result; previousValue = v; if (options.multiple) { var words = trimWords($input.val()); if (words.length > 1) { var seperator = options.multipleSeparator.length; var cursorAt = $(input).selection().start; var wordAt, progress = 0; $.each(words, function (i, word) { progress += word.length; if (cursorAt <= progress) { wordAt = i; return false; } progress += seperator; }); words[wordAt] = v; v = words.join(options.multipleSeparator); } v += options.multipleSeparator; } $input.val(v); hideResultsNow(); $input.trigger("result", [selected.data, selected.value]); return true; } function onChange(crap, skipPrevCheck) { if (lastKeyPressCode == KEY.DEL) { select.hide(); return; } var currentValue = $input.val(); if (!skipPrevCheck && currentValue == previousValue) return; previousValue = currentValue; currentValue = lastWord(currentValue); if (currentValue.length >= options.minChars) { $input.addClass(options.loadingClass); if (!options.matchCase) currentValue = currentValue.toLowerCase(); request(currentValue, receiveData, hideResultsNow); } else { stopLoading(); select.hide(); } }; function trimWords(value) { if (!value) return [""]; if (!options.multiple) return [$.trim(value)]; return $.map(value.split(options.multipleSeparator), function (word) { return $.trim(value).length ? $.trim(word) : null; }); } function lastWord(value) { if (!options.multiple) return value; var words = trimWords(value); if (words.length == 1) return words[0]; var cursorAt = $(input).selection().start; if (cursorAt == value.length) { words = trimWords(value) } else { words = trimWords(value.replace(value.substring(cursorAt), "")); } return words[words.length - 1]; } function autoFill(q, sValue) { if (options.autoFill && (lastWord($input.val()).toLowerCase() == q.toLowerCase()) && lastKeyPressCode != KEY.BACKSPACE) { $input.val($input.val() + sValue.substring(lastWord(previousValue).length)); $(input).selection(previousValue.length, previousValue.length + sValue.length); } }; function hideResults() { clearTimeout(timeout); timeout = setTimeout(hideResultsNow, 200); }; function hideResultsNow() { var wasVisible = select.visible(); select.hide(); clearTimeout(timeout); stopLoading(); if (options.mustMatch) { $input.search(function (result) { if (!result) { if (options.multiple) { var words = trimWords($input.val()).slice(0, -1); $input.val(words.join(options.multipleSeparator) + (words.length ? options.multipleSeparator : "")); } else { $input.val(""); $input.trigger("result", null); } } }); } }; function receiveData(q, data) { if (data && data.length && hasFocus) { stopLoading(); select.display(data, q); autoFill(q, data[0].value); select.show(); } else { hideResultsNow(); } }; function request(term, success, failure) { if (!options.matchCase) term = term.toLowerCase(); var data = cache.load(term); if (data && data.length) { success(term, data); } else if ((typeof options.url == "string") && (options.url.length > 0)) { var extraParams = { timestamp: +new Date() }; $.each(options.extraParams, function (key, param) { extraParams[key] = typeof param == "function" ? param() : param; }); $.ajax({ mode: "abort", port: "autocomplete" + input.name, dataType: options.dataType, url: options.url, data: $.extend({ q: lastWord(term), limit: options.max }, extraParams), success: function (data) { var parsed = options.parse && options.parse(data) || parse(data); cache.add(term, parsed); success(term, parsed); } }); } else { select.emptyList(); failure(term); } }; function parse(data) { var parsed = []; var rows = data.split("\n"); for (var i = 0; i < rows.length; i++) { var row = $.trim(rows[i]); if (row) { row = row.split("|"); parsed[parsed.length] = { data: row, value: row[0], result: options.formatResult && options.formatResult(row, row[0]) || row[0] }; } } return parsed; }; function stopLoading() { $input.removeClass(options.loadingClass); }; }; $.Autocompleter.defaults = { inputClass: "ac_input", resultsClass: "ac_results", loadingClass: "ac_loading", minChars: 1, delay: 400, matchCase: false, matchSubset: true, matchContains: false, cacheLength: 10, max: 100, mustMatch: false, extraParams: {}, selectFirst: true, formatItem: function (row) { return row[0]; }, formatMatch: null, autoFill: false, width: 0, multiple: false, multipleSeparator: ", ", highlight: function (value, term) { return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>"); }, scroll: true, scrollHeight: 180 }; $.Autocompleter.Cache = function (options) {
    var data = {}; var length = 0; function matchSubset(s, sub) { if (!options.matchCase) s = s.toLowerCase(); var i = s.indexOf(sub); if (options.matchContains == "word") { i = s.toLowerCase().search("\\b" + sub.toLowerCase()); } if (i == -1) return false; return i == 0 || options.matchContains; }; function add(q, value) { if (length > options.cacheLength) { flush(); } if (!data[q]) { length++; } data[q] = value; } function populate() { if (!options.data) return false; var stMatchSets = {}, nullData = 0; if (!options.url) options.cacheLength = 1; stMatchSets[""] = []; for (var i = 0, ol = options.data.length; i < ol; i++) { var rawValue = options.data[i]; rawValue = (typeof rawValue == "string") ? [rawValue] : rawValue; var value = options.formatMatch(rawValue, i + 1, options.data.length); if (value === false) continue; var firstChar = value.charAt(0).toLowerCase(); if (!stMatchSets[firstChar]) stMatchSets[firstChar] = []; var row = { value: value, data: rawValue, result: options.formatResult && options.formatResult(rawValue) || value }; stMatchSets[firstChar].push(row); if (nullData++ < options.max) { stMatchSets[""].push(row); } }; $.each(stMatchSets, function (i, value) { options.cacheLength++; add(i, value); }); } setTimeout(populate, 25); function flush() { data = {}; length = 0; } return { flush: flush, add: add, populate: populate, load: function (q) {
      if (!options.cacheLength || !length) return null; if (!options.url && options.matchContains) { var csub = []; for (var k in data) { if (k.length > 0) { var c = data[k]; $.each(c, function (i, x) { if (matchSubset(x.value, q)) { csub.push(x); } }); } } return csub; } else
        if (data[q]) { return data[q]; } else
          if (options.matchSubset) { for (var i = q.length - 1; i >= options.minChars; i--) { var c = data[q.substr(0, i)]; if (c) { var csub = []; $.each(c, function (i, x) { if (matchSubset(x.value, q)) { csub[csub.length] = x; } }); return csub; } } } return null;
    } 
    };
  }; $.Autocompleter.Select = function (options, input, select, config) { var CLASSES = { ACTIVE: "ac_over" }; var listItems, active = -1, data, term = "", needsInit = true, element, list; function init() { if (!needsInit) return; element = $("<div/>").hide().addClass(options.resultsClass).css("position", "absolute").appendTo(document.body); list = $("<ul/>").appendTo(element).mouseover(function (event) { if (target(event).nodeName && target(event).nodeName.toUpperCase() == 'LI') { active = $("li", list).removeClass(CLASSES.ACTIVE).index(target(event)); $(target(event)).addClass(CLASSES.ACTIVE); } }).click(function (event) { $(target(event)).addClass(CLASSES.ACTIVE); select(); input.focus(); return false; }).mousedown(function () { config.mouseDownOnSelect = true; }).mouseup(function () { config.mouseDownOnSelect = false; }); if (options.width > 0) element.css("width", options.width); needsInit = false; } function target(event) { var element = event.target; while (element && element.tagName != "LI") element = element.parentNode; if (!element) return []; return element; } function moveSelect(step) { listItems.slice(active, active + 1).removeClass(CLASSES.ACTIVE); movePosition(step); var activeItem = listItems.slice(active, active + 1).addClass(CLASSES.ACTIVE); if (options.scroll) { var offset = 0; listItems.slice(0, active).each(function () { offset += this.offsetHeight; }); if ((offset + activeItem[0].offsetHeight - list.scrollTop()) > list[0].clientHeight) { list.scrollTop(offset + activeItem[0].offsetHeight - list.innerHeight()); } else if (offset < list.scrollTop()) { list.scrollTop(offset); } } }; function movePosition(step) { active += step; if (active < 0) { active = listItems.size() - 1; } else if (active >= listItems.size()) { active = 0; } } function limitNumberOfItems(available) { return options.max && options.max < available ? options.max : available; } function fillList() { list.empty(); var max = limitNumberOfItems(data.length); for (var i = 0; i < max; i++) { if (!data[i]) continue; var formatted = options.formatItem(data[i].data, i + 1, max, data[i].value, term); if (formatted === false) continue; var li = $("<li/>").html(options.highlight(formatted, term)).addClass(i % 2 == 0 ? "ac_even" : "ac_odd").appendTo(list)[0]; $.data(li, "ac_data", data[i]); } listItems = list.find("li"); if (options.selectFirst) { listItems.slice(0, 1).addClass(CLASSES.ACTIVE); active = 0; } if ($.fn.bgiframe) list.bgiframe(); } return { display: function (d, q) { init(); data = d; term = q; fillList(); }, next: function () { moveSelect(1); }, prev: function () { moveSelect(-1); }, pageUp: function () { if (active != 0 && active - 8 < 0) { moveSelect(-active); } else { moveSelect(-8); } }, pageDown: function () { if (active != listItems.size() - 1 && active + 8 > listItems.size()) { moveSelect(listItems.size() - 1 - active); } else { moveSelect(8); } }, hide: function () { element && element.hide(); listItems && listItems.removeClass(CLASSES.ACTIVE); active = -1; }, visible: function () { return element && element.is(":visible"); }, current: function () { return this.visible() && (listItems.filter("." + CLASSES.ACTIVE)[0] || options.selectFirst && listItems[0]); }, show: function () { var offset = $(input).offset(); element.css({ width: typeof options.width == "string" || options.width > 0 ? options.width : $(input).width(), top: offset.top + input.offsetHeight, left: offset.left }).show(); if (options.scroll) { list.scrollTop(0); list.css({ maxHeight: options.scrollHeight, overflow: 'auto' }); if ($.browser.msie && typeof document.body.style.maxHeight === "undefined") { var listHeight = 0; listItems.each(function () { listHeight += this.offsetHeight; }); var scrollbarsVisible = listHeight > options.scrollHeight; list.css('height', scrollbarsVisible ? options.scrollHeight : listHeight); if (!scrollbarsVisible) { listItems.width(list.width() - parseInt(listItems.css("padding-left")) - parseInt(listItems.css("padding-right"))); } } } }, selected: function () { var selected = listItems && listItems.filter("." + CLASSES.ACTIVE).removeClass(CLASSES.ACTIVE); return selected && selected.length && $.data(selected[0], "ac_data"); }, emptyList: function () { list && list.empty(); }, unbind: function () { element && element.remove(); } }; }; $.fn.selection = function (start, end) { if (start !== undefined) { return this.each(function () { if (this.createTextRange) { var selRange = this.createTextRange(); if (end === undefined || start == end) { selRange.move("character", start); selRange.select(); } else { selRange.collapse(true); selRange.moveStart("character", start); selRange.moveEnd("character", end); selRange.select(); } } else if (this.setSelectionRange) { this.setSelectionRange(start, end); } else if (this.selectionStart) { this.selectionStart = start; this.selectionEnd = end; } }); } var field = this[0]; if (field.createTextRange) { var range = document.selection.createRange(), orig = field.value, teststring = "<->", textLength = range.text.length; range.text = teststring; var caretAt = field.value.indexOf(teststring); field.value = orig; this.selection(caretAt, caretAt + textLength); return { start: caretAt, end: caretAt + textLength} } else if (field.selectionStart !== undefined) { return { start: field.selectionStart, end: field.selectionEnd} } };
})(jQuery);


// Find X Positions of an Object
function icast_FindPosX(obj) {
  var left = 0;
  if (obj.offsetParent)
    while (1) {
      left += obj.offsetLeft;
      if (!obj.offsetParent)
        break;
      obj = obj.offsetParent;
    }
  else if (obj.x)
    left += obj.x;
  return left;
}

// Find Y Position of an Object
function icast_FindPosY(obj) {
  var top = 0;
  if (obj.offsetParent)
    while (1) {
      top += obj.offsetTop;
      if (!obj.offsetParent)
        break;
      obj = obj.offsetParent;
    }
  else if (obj.y)
    top += obj.y;
  return top;
}


// 10 Day Forecast Interaction
function icast_ChangeDay(dayNumber) {
  for (var i = 0; i < 10; i++) {
    if (dayNumber == i) {
      jQuery("#icast_dow" + i).addClass("icast_Selected");
      jQuery("#icast_fwx" + i).addClass("icast_FWXSelected");
      jQuery("#icast_detail" + i).addClass("icast_Selected");
    }
    else {
      jQuery("#icast_dow" + i).removeClass("icast_Selected");
      jQuery("#icast_fwx" + i).removeClass("icast_FWXSelected");
      jQuery("#icast_detail" + i).removeClass("icast_Selected");
    } 
  } 
}

// Location Search Functions
function icast_Swipe(state) {
  var icast_text = icast_Text_EnterCity;
  if (state == 'on' && jQuery("#icast_searchBox").val() == icast_text) {
    jQuery("#icast_searchBox").val(""); jQuery("#icast_searchBox").css("font-size", "11px"); jQuery("#icast_searchBox").css("color", "#454545");
  }
  else if (jQuery("#icast_searchBox").val() == "") {
    jQuery("#icast_searchBox").val(icast_text); jQuery("#icast_searchBox").css("font-size", "10px"); jQuery("#icast_searchBox").css("color", "#999");
  }
}


// Set New Location - Remains on Current Page - Uses jquery plugin for query object http://plugins.jquery.com/project/query-object
function icast_NewLocationReload(locationId) {
  var icast_Page = jQuery.query.get("icast_page");
  if (icast_Page == "")
    icast_Page = "/Local/Weather";
  var icast_Querystring = jQuery.query.remove("icast_page").remove("icast_location").remove("icast_day").remove("icast_month").remove("icast_chart").remove("icast_unit");
  if (icast_Querystring == "")
    var icast_newUrl = window.location.protocol + "//" + window.location.host + window.location.pathname + "?icast_page=" + icast_Page + "&icast_location=" + locationId;
  else
    var icast_newUrl = window.location.protocol + "//" + window.location.host + window.location.pathname + icast_Querystring + "&icast_page=" + icast_Page + "&icast_location=" + locationId;

  window.location.href = icast_newUrl;
}


// Location Search Autocomplete
var host = "http://www.intellicast.com/Search.axd";
var swipeText = icast_Text_EnterCity;

jQuery(document).ready(function () {
	// Get Location of Widget inside Host Page and then Set to Top
	var icast_ScrollDaily = icast_GetCookie("icast_Scroll");
	if (icast_ScrollDaily == "true") {
		// Verify User is actively using Daily
		var icast_Page = jQuery.query.get("icast_page");
		if (icast_Page != "") {
			var icast_widgetLocation_X = icast_FindPosX(icast_widgetNavigation);
			var icast_widgetLocation_Y = icast_FindPosY(icast_widgetNavigation);
			//window.alert('Widget Location in Page = ' + 'X:' + icast_widgetLocation_X + ' / Y:' + icast_widgetLocation_Y);
			window.scrollTo(icast_widgetLocation_X, icast_widgetLocation_Y);
		}
	}

	// Get Language and Set Language Variables
	jQuery(document).ready(function () {
		cookie = icast_GetCookie("icast_Language");
		if (cookie != null && cookie != "")
			icast_Language = cookie;

		if (icast_Language.toLocaleString().toUpperCase().substr(0, 3) == 'ES-') {
			//icast_Text_EnterCity = 'Ingrese Ciudad, Estado, País, o Código postal de Estados Unidos';
			icast_Text_EnterCity = '';
			icast_Text_Close = 'Cerrar';
			icast_Text_MultipleMatches = 'Multiples opciones encontradas';
			icast_Text_SearchNoResults = 'Su búsqueda no dio resultados';
			icast_Text_PleaseCheckSpelling = 'Por favor revise su ortografía<br />o intente una localidad cercana.';
			icast_Text_LocationSaved = '¡Localizacion grabada!';
			icast_Text_UnitedStates = 'Estados Unidos';
			icast_Text_ProvideValidEmail = 'Por favor proporcione una direccion valida de correo electronico.';
			icast_Text_PasswordCharLength = 'La clave debe contener al menos 6 caracteres y no mas de 30.';
			icast_Text_PasswordAndConfirmationNotMatch = 'Clave y confirmacion no coinciden.';
			icast_Text_SelectForecastLocation = 'Por favor seleccione una localizacion de pronostico.';
			icast_Text_AcceptsTermsAndPrivacy = 'Ud debe aceptar las reglas referentes a terminos de uso y privacidad.';
			icast_Text_ProvideValidUsername = 'Por favor proporcione un nombre de usuario valido.';
			icast_Text_SpecifyPassword = 'Por favor especifique su clave.';
			icast_Text_SpecifyCurrentPassword = 'Pro favor especifique su clave corriente.';
			icast_Text_NewPasswordCharLength = 'Nueva clave debe contener al menos 6 caracteres y no mas de 30.';
			icast_Text_NewPasswordAndConfirmationNotMatch = 'Nueva clave y confirmacion no coinciden.';
			icast_Text_VerifyUnsubscribe = '¿Seguro que desea retirar su registración de correos del clima?';
		}
		else {
			icast_Text_EnterCity = 'Enter City, State, Country, or US Zip Code';
			icast_Text_Close = 'Close';
			icast_Text_MultipleMatches = 'Multiple Matches Found';
			icast_Text_SearchNoResults = 'Your search did not return any results.';
			icast_Text_PleaseCheckSpelling = 'Please check your spelling<br />or try a nearby location.';
			icast_Text_LocationSaved = 'Location Saved!';
			icast_Text_UnitedStates = 'United States';
			icast_Text_ProvideValidEmail = 'Please provide a valid e-mail address.';
			icast_Text_PasswordCharLength = 'Password must be at least 6 characters long and less than 30 characters.';
			icast_Text_PasswordAndConfirmationNotMatch = 'Password and confirmation do not match.';
			icast_Text_SelectForecastLocation = 'Please select a forecast location.';
			icast_Text_AcceptsTermsAndPrivacy = 'You must accept the terms of use and privacy policy.';
			icast_Text_ProvideValidUsername = 'Please provide a valid username.';
			icast_Text_SpecifyPassword = 'Please specify your password.';
			icast_Text_SpecifyCurrentPassword = 'Please specify your current password.';
			icast_Text_NewPasswordCharLength = 'New password must be at least 6 characters long and less than 30 characters.';
			icast_Text_NewPasswordAndConfirmationNotMatch = 'New password and confirmation do not match.';
			icast_Text_VerifyUnsubscribe = 'Are you sure you want to unsubscribe from the weather email?';
		}
	});


	jQuery("#icast_searchBox").autocomplete(host + "?filter=" + icast_SearchFilter, {
		dataType: 'jsonp',
		parse: function (data) {
			var rows = new Array();

			//if (data.results.locations.location[i].name.indexOf(", " + icast_SearchLimit) != -1)
			
			for (var i = 0; i < data.results.count; i++) {
				rows[i] = { data: data.results.locations.location[i], value: data.results.locations.location[i].name, result: data.results.locations.location[i].name };
			}
			return rows;
		},
		minChars: 3,
		formatItem: function (row, i, n) {
			var rowNameLong = row.name;
			var rowNameShort = rowNameLong.replace(", United States", "");

			var rowNameShortLength = rowNameShort.length;
			if (rowNameShortLength > 30) {
				var rowNameShortAbbr = rowNameShort.substring(0, 30);
				return rowNameShortAbbr + "...";
			}
			else
				return rowNameShort;
		}
	});

	jQuery("#icast_searchBox").result(function (event, data, formatted) {
		var rowNameLong = formatted;
		var rowNameShort = rowNameLong.replace(", United States", "");

		var rowNameShortLength = rowNameShort.length;
		if (rowNameShortLength > 30) {
			var rowNameShortAbbr = rowNameShort.substring(0, 30);
			jQuery("#icast_searchBox").val(rowNameShortAbbr + "...");
		}
		else
			jQuery("#icast_searchBox").val(rowNameShort);

		icast_SearchAuto(data.id);
	});
});

// Search
function icast_SearchAuto(locationId) {
  if (jQuery("#icast_searchBox").val().length == 0 || jQuery("#icast_searchBox").val() == swipeText)
  	return;
  jQuery.getJSON(host + "?callback=?&q=" + jQuery("#icast_searchBox").val() + "&filter=" + icast_SearchFilter,
  function (data) {
    icast_NewLocationReload(locationId);
  });
}

// Search
function icast_Search() {
  if (jQuery("#icast_searchBox").val().length == 0 || jQuery("#icast_searchBox").val() == swipeText)
    return;

  jQuery.getJSON(host + "?callback=?&q=" + $("#icast_searchBox").val() + "&filter=" + icast_SearchFilter,
    function (data) {
    	switch (data.results.count) {
    		case 0:
    			jQuery("#icast_searchResults").css("display", "block");
    			jQuery("#icast_searchResults").html("<table style='background-color:#fff;border:solid 1px #eee;opacity:0.98;filter:alpha(opacity=98);position:absolute;margin-top:15px;margin-left:10px;height:77px;width:287px;'><tr><td style='font-family:Tahoma, Verdana, Arial, Helvetica, Sans-Serif;padding:10px;color:#990000;font-size:12px;font-weight:bold;white-space:nowrap;'>" + icast_Text_SearchNoResults + "<br /><span style='font-weight:normal;color:Black;'>" + icast_Text_PleaseCheckSpelling + "</span></td><td style='padding:5px;vertical-align:top;'><img src='http://images.intellicast.com/App_Images/btn_close.gif' style='cursor:pointer;' alt='" + icast_Text_Close + "' onclick='javascript:$(\"#icast_searchResults\").css(\"display\",\"none\");' /></td></tr></table>");
    			break;
    		case 1:
   				icast_NewLocationReload(data.results.locations.location[0].id);
    			break;
    		default:
    			jQuery("#icast_searchResults").css("display", "block");
    			var sb = new StringBuilder();

    			sb.append("<div style='background-color:#fff;border:solid 1px #eee;opacity:0.98;filter:alpha(opacity=98);position:absolute;margin-top:15px;margin-left:10px;padding:5px;height:250px;width:275px;overflow:auto;'>");
    			sb.append("<span style='font-family:Tahoma, Verdana, Arial, Helvetica, Sans-Serif;color:#990000;font-size:12px;font-weight:bold;padding-left:50px;'>");
    			sb.append(icast_Text_MultipleMatches);
    			sb.append("</span>");
    			sb.append("<span style='padding-top:3px;padding-left:40px;position:absolute;'><img src='http://images.intellicast.com/App_Images/btn_close.gif' style='cursor:pointer;' alt='");
    			sb.append(icast_Text_Close);

    			sb.append("' onclick='javascript:$(\"#icast_searchResults\").css(\"display\",\"none\");' /></span>");

    			sb.append("<table style='margin-top:5px;'>");
    			for (var i = 0; i < data.results.count; i++) {
    				sb.append("<tr style='cursor:pointer;' onMouseOver='this.className=\"icast_SearchLocationSelected\";' onMouseOut='this.className=\"\";'><td><a style='font-size:13px;font-family:Tahoma, Verdana, Arial, Helvetica, Sans-Serif;' onclick='javascript:icast_NewLocationReload(\"");
    				sb.append(data.results.locations.location[i].id);
    				sb.append("\");$(\"#icast_searchResults\").css(\"display\",\"none\");'>");

    				var locationName = data.results.locations.location[i].name;
    				locationName = locationName.replace(", United States", "");
    				if (locationName.length > 33)
    					locationName = locationName.substring(0, 33) + "...";

    				sb.append(locationName);
    				sb.append("</a></td></tr>");
    			}
    			sb.append("</table>");

    			sb.append("<span style='padding-top:3px;padding-left:210px;position:absolute;font-size:12px;'><img src='http://images.intellicast.com/App_Images/btn_close.gif' style='cursor:pointer;' alt='" + icast_Text_Close + "' onclick='javascript:$(\"#icast_searchResults\").css(\"display\",\"none\");' />&nbsp;" + icast_Text_Close + "</span>");

    			sb.append("</div>");
    			$("#icast_searchResults").html(sb.toString());
    			break;
    	}
    });



//  jQuery.getJSON(host + "?callback=?&q=" + jQuery("#icast_searchBox").val(),
//  function (data) {
//    icast_NewLocationReload(data.results.locations.location[0].id);
//  });
}



// Quick View Command
function quickView(command) {
  if (eval(map)) {
    switch (command) {
      case "Radar":
        map.setMapLayers('hdRadarSmoothPaletteA');
        map.setTransparency(.7);
        break;
      case "StormRadar":
        map.setMapLayers('hdRadarSmoothPaletteA,StormCellCurrent');
        map.setTransparency(.7);
        break;
      case "StormCell":
        map.setMapLayers('hdRadarSmoothPaletteA,StormCellCurrent');
        map.setTransparency(.7);
        break;
      case "Cloud":
        map.setMapLayers('hdVisSatIRBlend');
        map.setTransparency(1);
        break;
      case "Lightning":
        map.setMapLayers('hdRadarSmoothPaletteA,LightningSummary');
        map.setTransparency(.7);
        break;
      case "Driving":
        map.setMapLayers('drivecastSmooth');
        map.setTransparency(.7);
        break;
      case "Temps":
        map.setMapLayers('tempcon');
        map.setTransparency(.6);
        break;
      case "Temperature":
        map.setMapLayers('tempcon');
        map.setTransparency(.6);
        break;
      case "Fire":
        map.setMapLayers('fireconSmooth');
        map.setTransparency(.6);
        break;
      case "Fires":
        map.setMapLayers('fireconSmooth');
        map.setTransparency(.6);
        break;
      case "Earthquake":
        map.setMapLayers('EarthquakesRecent');
        map.setTransparency(.7);
        break;
      case "Snow":
        map.setMapLayers('snowdepthSmooth');
        map.setTransparency(.7);
        break;
      case "FullScreen":
        location.href = '/Local/Map.aspx';
        break;
    }
  }
}


// Javascript Stringbuilder Function
function StringBuilder(value) { this.strings = new Array(""); this.append(value); }
StringBuilder.prototype.append = function (value) { if (value) { this.strings.push(value); } }
StringBuilder.prototype.clear = function () { this.strings.length = 1; }
StringBuilder.prototype.toString = function () { return this.strings.join(""); }

/**********************************
* FusionCharts: Flash Player detection and Chart embedding.
* Version: 1.2 (1st November, 2007) - Added Player detection, New conditional fixes for IE, New FORM fixes for IE 
* Version: 1.1 (29th June, 2007) - Added Player detection, New conditional fixes for IE
*
* Morphed from SWFObject (http://blog.deconcept.com/swfobject/) under MIT License:
* http://www.opensource.org/licenses/mit-license.php
*
*/
if (typeof infosoftglobal == "undefined") var infosoftglobal = new Object();
if (typeof infosoftglobal.FusionChartsUtil == "undefined") infosoftglobal.FusionChartsUtil = new Object();
infosoftglobal.FusionCharts = function (swf, id, w, h, debugMode, registerWithJS, c, scaleMode, lang, detectFlashVersion, autoInstallRedirect) {
  if (!document.getElementById) { return; }

  //Flag to see whether data has been set initially
  this.initialDataSet = false;

  //Create container objects
  this.params = new Object();
  this.variables = new Object();
  this.attributes = new Array();

  //Set attributes for the SWF
  if (swf) { this.setAttribute('swf', swf); }
  if (id) { this.setAttribute('id', id); }
  if (w) { this.setAttribute('width', w); }
  if (h) { this.setAttribute('height', h); }

  //Set background color
  if (c) { this.addParam('bgcolor', c); }

  //Set Quality	
  this.addParam('quality', 'high');

  //Add scripting access parameter
  this.addParam('allowScriptAccess', 'always');

  //Pass width and height to be appended as chartWidth and chartHeight
  this.addVariable('chartWidth', w);
  this.addVariable('chartHeight', h);

  //Whether in debug mode
  debugMode = debugMode ? debugMode : 0;
  this.addVariable('debugMode', debugMode);
  //Pass DOM ID to Chart
  this.addVariable('DOMId', id);
  //Whether to registed with JavaScript
  registerWithJS = registerWithJS ? registerWithJS : 0;
  this.addVariable('registerWithJS', registerWithJS);

  //Scale Mode of chart
  scaleMode = scaleMode ? scaleMode : 'noScale';
  this.addVariable('scaleMode', scaleMode);

  //Application Message Language
  lang = lang ? lang : 'EN';
  this.addVariable('lang', lang);

  //Whether to auto detect and re-direct to Flash Player installation
  this.detectFlashVersion = detectFlashVersion ? detectFlashVersion : 1;
  this.autoInstallRedirect = autoInstallRedirect ? autoInstallRedirect : 1;

  //Ger Flash Player version 
  this.installedVer = infosoftglobal.FusionChartsUtil.getPlayerVersion();

  if (!window.opera && document.all && this.installedVer.major > 7) {
    // Only add the onunload cleanup if the Flash Player version supports External Interface and we are in IE
    infosoftglobal.FusionCharts.doPrepUnload = true;
  }
}

infosoftglobal.FusionCharts.prototype = {
  setAttribute: function (name, value) {
    this.attributes[name] = value;
  },
  getAttribute: function (name) {
    return this.attributes[name];
  },
  addParam: function (name, value) {
    this.params[name] = value;
  },
  getParams: function () {
    return this.params;
  },
  addVariable: function (name, value) {
    this.variables[name] = value;
  },
  getVariable: function (name) {
    return this.variables[name];
  },
  getVariables: function () {
    return this.variables;
  },
  getVariablePairs: function () {
    var variablePairs = new Array();
    var key;
    var variables = this.getVariables();
    for (key in variables) {
      variablePairs.push(key + "=" + variables[key]);
    }
    return variablePairs;
  },
  getSWFHTML: function () {
    var swfNode = "";
    if (navigator.plugins && navigator.mimeTypes && navigator.mimeTypes.length) {
      // netscape plugin architecture			
      swfNode = '<embed type="application/x-shockwave-flash" src="' + this.getAttribute('swf') + '" width="' + this.getAttribute('width') + '" height="' + this.getAttribute('height') + '"  ';
      swfNode += ' id="' + this.getAttribute('id') + '" name="' + this.getAttribute('id') + '" ';
      var params = this.getParams();
      for (var key in params) { swfNode += [key] + '="' + params[key] + '" '; }
      var pairs = this.getVariablePairs().join("&");
      if (pairs.length > 0) { swfNode += 'flashvars="' + pairs + '"'; }
      swfNode += '/>';
    } else { // PC IE			
      swfNode = '<object id="' + this.getAttribute('id') + '" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="' + this.getAttribute('width') + '" height="' + this.getAttribute('height') + '">';
      swfNode += '<param name="movie" value="' + this.getAttribute('swf') + '" />';
      var params = this.getParams();
      for (var key in params) {
        swfNode += '<param name="' + key + '" value="' + params[key] + '" />';
      }
      var pairs = this.getVariablePairs().join("&");
      if (pairs.length > 0) { swfNode += '<param name="flashvars" value="' + pairs + '" />'; }
      swfNode += "</object>";
    }
    return swfNode;
  },
  setDataURL: function (strDataURL) {
    //This method sets the data URL for the chart.
    //If being set initially
    if (this.initialDataSet == false) {
      this.addVariable('dataURL', strDataURL);
      //Update flag
      this.initialDataSet = true;
    } else {
      //Else, we update the chart data using External Interface
      //Get reference to chart object
      var chartObj = infosoftglobal.FusionChartsUtil.getChartObject(this.getAttribute('id'));
      chartObj.setDataURL(strDataURL);
    }
  },
  setDataXML: function (strDataXML) {
    //If being set initially
    if (this.initialDataSet == false) {
      //This method sets the data XML for the chart INITIALLY.
      this.addVariable('dataXML', strDataXML);
      //Update flag
      this.initialDataSet = true;
    } else {
      //Else, we update the chart data using External Interface
      //Get reference to chart object
      var chartObj = infosoftglobal.FusionChartsUtil.getChartObject(this.getAttribute('id'));
      chartObj.setDataXML(strDataXML);
    }
  },
  setTransparent: function (isTransparent) {
    //Sets chart to transparent mode when isTransparent is true (default)
    //When no parameter is passed, we assume transparent to be true.
    if (typeof isTransparent == "undefined") {
      isTransparent = true;
    }
    //Set the property
    if (isTransparent)
      this.addParam('WMode', 'transparent');
    else
      this.addParam('WMode', 'Opaque');
  },

  render: function (elementId) {
    //First check for installed version of Flash Player - we need a minimum of 8
    if ((this.detectFlashVersion == 1) && (this.installedVer.major < 8)) {
      if (this.autoInstallRedirect == 1) {
        //If we can auto redirect to install the player?
        //var installationConfirm = window.confirm("You need Adobe Flash Player 8 (or above) to view the charts. It is a free and lightweight installation from Adobe.com. Please click on Ok to install the same.");
        //if (installationConfirm){
        //	window.location = "http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash";
        //}else{
        //	return false;
        //}
      } else {
        //Else, do not take an action. It means the developer has specified a message in the DIV (and probably a link).
        //So, expect the developers to provide a course of way to their end users.
        //window.alert("You need Adobe Flash Player 8 (or above) to view the charts. It is a free and lightweight installation from Adobe.com. ");
        return false;
      }
    } else {
      //Render the chart
      var n = (typeof elementId == 'string') ? document.getElementById(elementId) : elementId;
      n.innerHTML = this.getSWFHTML();

      //Added <FORM> compatibility
      //Check if it's added in Mozilla embed array or if already exits 
      if (!document.embeds[this.getAttribute('id')] && !window[this.getAttribute('id')])
        window[this.getAttribute('id')] = document.getElementById(this.getAttribute('id'));
      //or else document.forms[formName/formIndex][chartId]			
      return true;
    }
  }
}

/* ---- detection functions ---- */
infosoftglobal.FusionChartsUtil.getPlayerVersion = function () {
  var PlayerVersion = new infosoftglobal.PlayerVersion([0, 0, 0]);
  if (navigator.plugins && navigator.mimeTypes.length) {
    var x = navigator.plugins["Shockwave Flash"];
    if (x && x.description) {
      PlayerVersion = new infosoftglobal.PlayerVersion(x.description.replace(/([a-zA-Z]|\s)+/, "").replace(/(\s+r|\s+b[0-9]+)/, ".").split("."));
    }
  } else if (navigator.userAgent && navigator.userAgent.indexOf("Windows CE") >= 0) {
    //If Windows CE
    var axo = 1;
    var counter = 3;
    while (axo) {
      try {
        counter++;
        axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash." + counter);
        PlayerVersion = new infosoftglobal.PlayerVersion([counter, 0, 0]);
      } catch (e) {
        axo = null;
      }
    }
  } else {
    // Win IE (non mobile)
    // Do minor version lookup in IE, but avoid Flash Player 6 crashing issues
    try {
      var axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
    } catch (e) {
      try {
        var axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");
        PlayerVersion = new infosoftglobal.PlayerVersion([6, 0, 21]);
        axo.AllowScriptAccess = "always"; // error if player version < 6.0.47 (thanks to Michael Williams @ Adobe for this code)
      } catch (e) {
        if (PlayerVersion.major == 6) {
          return PlayerVersion;
        }
      }
      try {
        axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
      } catch (e) { }
    }
    if (axo != null) {
      PlayerVersion = new infosoftglobal.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));
    }
  }
  return PlayerVersion;
}
infosoftglobal.PlayerVersion = function (arrVersion) {
  this.major = arrVersion[0] != null ? parseInt(arrVersion[0]) : 0;
  this.minor = arrVersion[1] != null ? parseInt(arrVersion[1]) : 0;
  this.rev = arrVersion[2] != null ? parseInt(arrVersion[2]) : 0;
}
// ------------ Fix for Out of Memory Bug in IE in FP9 ---------------//
/* Fix for video streaming bug */
infosoftglobal.FusionChartsUtil.cleanupSWFs = function () {
  var objects = document.getElementsByTagName("OBJECT");
  for (var i = objects.length - 1; i >= 0; i--) {
    objects[i].style.display = 'none';
    for (var x in objects[i]) {
      if (typeof objects[i][x] == 'function') {
        objects[i][x] = function () { };
      }
    }
  }
}
// Fixes bug in fp9
if (infosoftglobal.FusionCharts.doPrepUnload) {
  if (!infosoftglobal.unloadSet) {
    infosoftglobal.FusionChartsUtil.prepUnload = function () {
      __flash_unloadHandler = function () { };
      __flash_savedUnloadHandler = function () { };
      window.attachEvent("onunload", infosoftglobal.FusionChartsUtil.cleanupSWFs);
    }
    window.attachEvent("onbeforeunload", infosoftglobal.FusionChartsUtil.prepUnload);
    infosoftglobal.unloadSet = true;
  }
}
/* Add document.getElementById if needed (mobile IE < 5) */
if (!document.getElementById && document.all) { document.getElementById = function (id) { return document.all[id]; } }
/* Add Array.push if needed (ie5) */
if (Array.prototype.push == null) { Array.prototype.push = function (item) { this[this.length] = item; return this.length; } }

/* Function to return Flash Object from ID */
infosoftglobal.FusionChartsUtil.getChartObject = function (id) {
  var chartRef = null;
  if (navigator.appName.indexOf("Microsoft Internet") == -1) {
    if (document.embeds && document.embeds[id])
      chartRef = document.embeds[id];
    else
      chartRef = window.document[id];
  }
  else {
    chartRef = window[id];
  }
  if (!chartRef)
    chartRef = document.getElementById(id);

  return chartRef;
}
/* Aliases for easy usage */
var getChartFromId = infosoftglobal.FusionChartsUtil.getChartObject;
var FusionCharts = infosoftglobal.FusionCharts;


function IsValidEmailAddress(emailAddress) {
  //var emailReg = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
  emailAddress = emailAddress.replace(/^\s+|\s+$/g, "");
  var emailReg = /^(([^<>()[\]\\.,;:\s@\"\'\|]+(\.[^<>()[\]\\.,;:\s@\"\'\|]+)*)|(\".+\"))@((\[(2([0-4]\d|5[0-5])|1?\d{1,2})(\.(2([0-4]\d|5[0-5])|1?\d{1,2})){3} \])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/

  var regex = new RegExp(emailReg);
  return regex.test(emailAddress);
}

/**
* jQuery.query - Query String Modification and Creation for jQuery
* Written by Blair Mitchelmore (blair DOT mitchelmore AT gmail DOT com)
* Licensed under the WTFPL (http://sam.zoy.org/wtfpl/).
* Date: 2009/8/13
*
* @author Blair Mitchelmore
* @version 2.1.7
*
**/
new function (settings) {
  // Various Settings
  var $separator = settings.separator || '&';
  var $spaces = settings.spaces === false ? false : true;
  var $suffix = settings.suffix === false ? '' : '[]';
  var $prefix = settings.prefix === false ? false : true;
  var $hash = $prefix ? settings.hash === true ? "#" : "?" : "";
  var $numbers = settings.numbers === false ? false : true;

  jQuery.query = new function () {
    var is = function (o, t) {
      return o != undefined && o !== null && (!!t ? o.constructor == t : true);
    };
    var parse = function (path) {
      var m, rx = /\[([^[]*)\]/g, match = /^([^[]+)(\[.*\])?$/.exec(path), base = match[1], tokens = [];
      while (m = rx.exec(match[2])) tokens.push(m[1]);
      return [base, tokens];
    };
    var set = function (target, tokens, value) {
      var o, token = tokens.shift();
      if (typeof target != 'object') target = null;
      if (token === "") {
        if (!target) target = [];
        if (is(target, Array)) {
          target.push(tokens.length == 0 ? value : set(null, tokens.slice(0), value));
        } else if (is(target, Object)) {
          var i = 0;
          while (target[i++] != null);
          target[--i] = tokens.length == 0 ? value : set(target[i], tokens.slice(0), value);
        } else {
          target = [];
          target.push(tokens.length == 0 ? value : set(null, tokens.slice(0), value));
        }
      } else if (token && token.match(/^\s*[0-9]+\s*$/)) {
        var index = parseInt(token, 10);
        if (!target) target = [];
        target[index] = tokens.length == 0 ? value : set(target[index], tokens.slice(0), value);
      } else if (token) {
        var index = token.replace(/^\s*|\s*$/g, "");
        if (!target) target = {};
        if (is(target, Array)) {
          var temp = {};
          for (var i = 0; i < target.length; ++i) {
            temp[i] = target[i];
          }
          target = temp;
        }
        target[index] = tokens.length == 0 ? value : set(target[index], tokens.slice(0), value);
      } else {
        return value;
      }
      return target;
    };

    var queryObject = function (a) {
      var self = this;
      self.keys = {};

      if (a.queryObject) {
        jQuery.each(a.get(), function (key, val) {
          self.SET(key, val);
        });
      } else {
        jQuery.each(arguments, function () {
          var q = "" + this;
          q = q.replace(/^[?#]/, ''); // remove any leading ? || #
          q = q.replace(/[;&]$/, ''); // remove any trailing & || ;
          if ($spaces) q = q.replace(/[+]/g, ' '); // replace +'s with spaces

          jQuery.each(q.split(/[&;]/), function () {
            var key = decodeURIComponent(this.split('=')[0] || "");
            var val = decodeURIComponent(this.split('=')[1] || "");

            if (!key) return;

            if ($numbers) {
              if (/^[+-]?[0-9]+\.[0-9]*$/.test(val)) // simple float regex
                val = parseFloat(val);
              else if (/^[+-]?[0-9]+$/.test(val)) // simple int regex
                val = parseInt(val, 10);
            }

            val = (!val && val !== 0) ? true : val;

            if (val !== false && val !== true && typeof val != 'number')
              val = val;

            self.SET(key, val);
          });
        });
      }
      return self;
    };

    queryObject.prototype = {
      queryObject: true,
      has: function (key, type) {
        var value = this.get(key);
        return is(value, type);
      },
      GET: function (key) {
        if (!is(key)) return this.keys;
        var parsed = parse(key), base = parsed[0], tokens = parsed[1];
        var target = this.keys[base];
        while (target != null && tokens.length != 0) {
          target = target[tokens.shift()];
        }
        return typeof target == 'number' ? target : target || "";
      },
      get: function (key) {
        var target = this.GET(key);
        if (is(target, Object))
          return jQuery.extend(true, {}, target);
        else if (is(target, Array))
          return target.slice(0);
        return target;
      },
      SET: function (key, val) {
        var value = !is(val) ? null : val;
        var parsed = parse(key), base = parsed[0], tokens = parsed[1];
        var target = this.keys[base];
        this.keys[base] = set(target, tokens.slice(0), value);
        return this;
      },
      set: function (key, val) {
        return this.copy().SET(key, val);
      },
      REMOVE: function (key) {
        return this.SET(key, null).COMPACT();
      },
      remove: function (key) {
        return this.copy().REMOVE(key);
      },
      EMPTY: function () {
        var self = this;
        jQuery.each(self.keys, function (key, value) {
          delete self.keys[key];
        });
        return self;
      },
      load: function (url) {
        var hash = url.replace(/^.*?[#](.+?)(?:\?.+)?$/, "$1");
        var search = url.replace(/^.*?[?](.+?)(?:#.+)?$/, "$1");
        return new queryObject(url.length == search.length ? '' : search, url.length == hash.length ? '' : hash);
      },
      empty: function () {
        return this.copy().EMPTY();
      },
      copy: function () {
        return new queryObject(this);
      },
      COMPACT: function () {
        function build(orig) {
          var obj = typeof orig == "object" ? is(orig, Array) ? [] : {} : orig;
          if (typeof orig == 'object') {
            function add(o, key, value) {
              if (is(o, Array))
                o.push(value);
              else
                o[key] = value;
            }
            jQuery.each(orig, function (key, value) {
              if (!is(value)) return true;
              add(obj, key, build(value));
            });
          }
          return obj;
        }
        this.keys = build(this.keys);
        return this;
      },
      compact: function () {
        return this.copy().COMPACT();
      },
      toString: function () {
        var i = 0, queryString = [], chunks = [], self = this;
        var encode = function (str) {
          str = str + "";
          if ($spaces) str = str.replace(/ /g, "+");
          return encodeURIComponent(str);
        };
        var addFields = function (arr, key, value) {
          if (!is(value) || value === false) return;
          var o = [encode(key)];
          if (value !== true) {
            o.push("=");
            o.push(encode(value));
          }
          arr.push(o.join(""));
        };
        var build = function (obj, base) {
          var newKey = function (key) {
            return !base || base == "" ? [key].join("") : [base, "[", key, "]"].join("");
          };
          jQuery.each(obj, function (key, value) {
            if (typeof value == 'object')
              build(value, newKey(key));
            else
              addFields(chunks, newKey(key), value);
          });
        };

        build(this.keys);

        if (chunks.length > 0) queryString.push($hash);
        queryString.push(chunks.join($separator));

        return queryString.join("");
      }
    };

    return new queryObject(location.search, location.hash);
  };
} (jQuery.query || {}); // Pass in jQuery.query as settings object



// Update Default Location Saved Text
function icast_UpdateDefaultLocationText(location) {
  //jQuery("#icast_saveDefaultLocationText").html("Your current default location is: <strong>" + location + "</strong>");
  jQuery("#icast_saveDefaultLocationText").html(icast_Text_LocationSaved);
}

function icast_SetEmailDefaultLocation(name, value, expires) {
  icast_SetCookie(name, value, expires);

  var icast_Querystring = jQuery.query.remove("icast_page").remove("icast_location").remove("icast_day").remove("icast_month").remove("icast_chart").remove("icast_unit");
  if (icast_Querystring == "")
    var icast_newUrl = window.location.protocol + "//" + window.location.host + window.location.pathname + "?icast_page=Local/Weather&icast_location=" + value;
  else
    var icast_newUrl = window.location.protocol + "//" + window.location.host + window.location.pathname + icast_Querystring + "&icast_page=Local/Weather&icast_location=" + value;

  window.location.href = icast_newUrl;
}


//user preferences
var icast_AuthId = "";
var icast_CityId = "";
var icast_TempUnit = "F";
var icast_Language = "en-US";
var icast_SearchFilter = "";

function icast_InitPrefs() {
  var cookie = icast_GetCookie("icast_AuthId");
  if (cookie != null && cookie != "")
    icast_AuthId = cookie;
  cookie = icast_GetCookie("icast_CityId");
  if (cookie != null && cookie != "")
    icast_CityId = cookie;
  cookie = icast_GetCookie("icast_TempUnit");
  if (cookie != null && cookie != "")
    icast_TempUnit = cookie;
  cookie = icast_GetCookie("icast_Language");
  if (cookie != null && cookie != "")
  	icast_Language = cookie;
  cookie = icast_GetCookie("icast_SearchFilter");
  if (cookie != null && cookie != "")
  	icast_SearchFilter = cookie;
}


//cookie functions
function icast_GetCookieVal(offset) {
  var endstr = document.cookie.indexOf(";", offset);
  if (endstr == -1) { endstr = document.cookie.length; }
  return unescape(document.cookie.substring(offset, endstr));
}

function icast_GetCookie(name) {
  var arg = name + "=";
  var alen = arg.length;
  var clen = document.cookie.length;
  var i = 0;
  while (i < clen) {
    var j = i + alen;
    if (document.cookie.substring(i, j) == arg) {
      return icast_GetCookieVal(j);
    }
    i = document.cookie.indexOf(" ", i) + 1;
    if (i == 0) break;
  }
  return null;
}

function icast_DeleteCookie(name, path, domain) {
  if (icast_GetCookie(name)) {
    document.cookie = name + "=" +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
    "; expires=Thu, 01-Jan-70 00:00:01 GMT";
  }
}

function icast_SetCookie(name, value, expires, path, domain, secure) {
  document.cookie = name + "=" + escape(value) +
    ((expires) ? "; expires=" + expires.toGMTString() : "") +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
    ((secure) ? "; secure" : "");
}

icast_InitPrefs();

//Membership functions
function icast_InitEmailCitySearch() {
  jQuery(document).ready(function () {
    var host = "http://www.intellicast.com/Search.axd";
    jQuery("#icast_emailCitySearch").autocomplete(host + "?filter=" + icast_SearchFilter, {
      dataType: 'jsonp',
      parse: function (data) {
        var rows = new Array();
        for (var i = 0; i < data.results.count; i++) {
          rows[i] = { data: data.results.locations.location[i], value: data.results.locations.location[i].name, result: data.results.locations.location[i].name };
        }
        return rows;
      },
      minChars: 3,
      formatItem: function (row, i, n) {
        return row.name
      }
    });
 
    jQuery("#icast_emailCitySearch").result(function (event, data, formatted) {
      jQuery("#icast_EmailCityId").val(data.id);
    });
  });
}



//appends querystring params to an existing querystring.
function icast_AppendQs() {
	var qs = jQuery.query.remove("icast_page").remove("icast_ec");
	if (qs != "") {
		return "&" + qs.toString().substring(1);
	}
	else
		return "";
}

function icast_SignUp() {
  if (!IsValidEmailAddress(jQuery("#icast_UserName").val())) {
    alert(icast_Text_ProvideValidEmail);
    jQuery("#icast_UserName").focus();
    return false;
  }

  if (jQuery("#icast_Password").val().length < 6 || jQuery("#icast_Password").val().length > 30) {
    alert(icast_Text_PasswordCharLength);
    jQuery("#icast_Password").focus();
    return false;
  }

  if (jQuery("#icast_Password").val() != jQuery("#icast_ConfirmPassword").val()) {
    alert(icast_Text_PasswordAndConfirmationNotMatch);
    jQuery("#icast_ConfirmPassword").focus();
    return false;
  }

  if (jQuery("#icast_EmailCityId").val() == "") {
    alert(icast_Text_SelectForecastLocation);
    jQuery("#icast_emailCitySearch").focus();
    return false;
  }

  if (!jQuery("#icast_termsAccepted").attr("checked")) {
    alert(icast_Text_AcceptsTermsAndPrivacy);
    jQuery("#icast_termsAccepted").focus();
    return false;
  }

  var url = "http://www.intellicast.com/WidgetBody.ajax?icast_page=/Membership/Signup/Submit"
  + "&icast_UserName=" + jQuery("#icast_UserName").val()
  + "&icast_Password=" + jQuery("#icast_Password").val()
  + "&icast_IsHtmlFormat=" + jQuery("#icast_IsHtmlFormat").val()
  + "&icast_EmailCityId=" + jQuery("#icast_EmailCityId").val()
  + "&icast_id=" + jQuery("#icast_id").val()
  + "&icast_TempUnit=" + icast_TempUnit
  + "&icast_IsMetric=" + jQuery("input[name='icast_IsMetric']:checked").val()
	+ icast_AppendQs();

  jQuery.ajax({
    type: "GET",
    url: url,
    success: function () { icast_ResponseCallback(); },
    dataType: "script"
  });
}

function icast_SignOut() {
	var url = "http://www.intellicast.com/WidgetBody.ajax?icast_page=/Membership/SignOut"
  + "&icast_id=" + jQuery("#icast_id").val()
  + "&icast_TempUnit=" + icast_TempUnit
  + icast_AppendQs();

  jQuery.ajax({
    type: "GET",
    url: url,
    success: function () { icast_ResponseCallback(); },
    dataType: "script"
  });
}

function icast_SignIn() {

  if (!IsValidEmailAddress(jQuery("#icast_SignInUserName").val())) {
    alert(icast_Text_ProvideValidUsername);
    jQuery("#icast_SignInUserName").focus();
    return false;
  }

  if (jQuery("#icast_SignInPassword").val().length == 0) {
    alert(icast_Text_SpecifyPassword);
    jQuery("#icast_SignInPassword").focus();
    return false;
  }

  var url = "http://www.intellicast.com/WidgetBody.ajax?icast_page=/Membership/SignIn/Submit"
  + "&icast_SignInUserName=" + jQuery("#icast_SignInUserName").val()
  + "&icast_SignInPassword=" + jQuery("#icast_SignInPassword").val()
  + "&icast_SignInPersist=" + jQuery("#icast_SignInPersist").attr("checked")
  + "&icast_TempUnit=" + icast_TempUnit
  + "&icast_id=" + jQuery("#icast_id").val()
	+ icast_AppendQs();

  jQuery.ajax({
    type: "GET",
    url: url,
    success: function () { icast_ResponseCallback(); },
    dataType: "script"
  });
}

function icast_SubmitEmailSettings() {
  if (!IsValidEmailAddress(jQuery("#icast_subEmail").val())) {
    alert(icast_Text_ProvideValidEmail);
    jQuery("#icast_subEmail").focus();
    return false;
  }

  if (jQuery("#icast_cityId").val() == "") {
    alert(icast_Text_SelectForecastLocation);
    jQuery("#icast_emailCitySearch").focus();
    return false;
  }

  var url = "http://www.intellicast.com/WidgetBody.ajax?icast_page=/Membership/EmailSettings/Submit"
  + "&icast_subEmail=" + jQuery("#icast_subEmail").val()
  + "&icast_IsHtmlFormat=" + jQuery("#icast_IsHtmlFormat").val()
  + "&icast_EmailCityId=" + jQuery("#icast_EmailCityId").val()
  + "&icast_id=" + jQuery("#icast_id").val()
  + "&icast_TempUnit=" + icast_TempUnit
  + "&icast_AuthId=" + icast_AuthId
  + "&icast_IsMetric=" + jQuery("input[name='icast_IsMetric']:checked").val()
	+ icast_AppendQs();

  jQuery.ajax({
    type: "GET",
    url: url,
    success: function () { icast_ResponseCallback(); },
    dataType: "script"
  });
}

function icast_ChangePass() {
  if (jQuery("#icast_CurrentPassword").val().length == 0) {
    alert(icast_Text_SpecifyCurrentPassword);
    jQuery("#icast_CurrentPassword").focus();
    return false;
  }

  if (jQuery("#icast_NewPassword").val().length < 6 || jQuery("#icast_NewPassword").val().length > 30) {
    alert(icast_Text_NewPasswordCharLength);
    jQuery("#icast_NewPassword").focus();
    return false;
  }

  if (jQuery("#icast_NewPassword").val() != jQuery("#icast_ConfirmNewPassword").val()) {
    alert(icast_Text_NewPasswordAndConfirmationNotMatch);
    jQuery("#icast_ConfirmNewPassword").focus();
    return false;
  }

  var url = "http://www.intellicast.com/WidgetBody.ajax?icast_page=/Membership/ChangePassword/Submit"
  + "&icast_CurrentPassword=" + jQuery("#icast_CurrentPassword").val()
  + "&icast_NewPassword=" + jQuery("#icast_NewPassword").val()
  + "&icast_UserId=" + jQuery("#icast_UserId").val()
  + "&icast_id=" + jQuery("#icast_id").val()
  + "&icast_TempUnit=" + icast_TempUnit
  + "&icast_AuthId=" + icast_AuthId
	+ icast_AppendQs();

  jQuery.ajax({
    type: "GET",
    url: url,
    success: function () { icast_ResponseCallback(); },
    dataType: "script"
  });
}

function icast_ResetPass() {
  if (!IsValidEmailAddress(jQuery("#icast_UserName").val())) {
    alert(icast_Text_ProvideValidEmail);
    jQuery("#icast_UserName").focus();
    return false;
  }

  var url = "http://www.intellicast.com/WidgetBody.ajax?icast_page=/Membership/ForgotPassword/Submit"
  + "&icast_UserName=" + jQuery("#icast_UserName").val()
  + "&icast_TempUnit=" + icast_TempUnit
  + "&icast_id=" + jQuery("#icast_id").val()
  + "&icast_AuthId=" + icast_AuthId
	+ icast_AppendQs();

  jQuery.ajax({
    type: "GET",
    url: url,
    success: function () { icast_ResponseCallback(); },
    dataType: "script"
  });
}

function icast_Unsubscribe() {
  if (confirm(icast_Text_VerifyUnsubscribe)) {
  	var url = "http://www.intellicast.com/WidgetBody.ajax?icast_page=/Membership/Unsubscribe/Submit"
    + "&icast_UserId=" + jQuery("#icast_UserId").val()
    + "&icast_id=" + jQuery("#icast_id").val()
    + "&icast_TempUnit=" + icast_TempUnit
    + "&icast_AuthId=" + icast_AuthId
		+ icast_AppendQs();

    jQuery.ajax({
      type: "GET",
      url: url,
      success: function () { icast_ResponseCallback(); },
      dataType: "script"
    });
  }
  else
    return false;
}

function icast_UnsubscribePublic() {
  if (!IsValidEmailAddress(jQuery("#icast_UserName").val())) {
    alert(icast_Text_ProvideValidEmail);
    jQuery("#icast_UserName").focus();
    return false;
  }

   var url = "http://www.intellicast.com/WidgetBody.ajax?icast_page=/Membership/Unsubscribe/Public/Submit"
  + "&icast_UserName=" + jQuery("#icast_UserName").val()
  + "&icast_id=" + jQuery("#icast_id").val()
  + "&icast_TempUnit=" + icast_TempUnit
  + "&icast_AuthId=" + icast_AuthId
	+ icast_AppendQs();

  jQuery.ajax({
    type: "GET",
    url: url,
    success: function () { icast_ResponseCallback(); },
    dataType: "script"
  });
}



//////// Weather Alerts Registration //////
function ShowAlertsDiv() {
//  if (jQuery("#AlertsLocation1").html() != "")
//    jQuery("#AlertsLocation1").css("display", "block");
//  if (jQuery("#AlertsLocation2").html() != "")
//    jQuery("#AlertsLocation2").css("display", "block");
//  if (jQuery("#AlertsLocation3").html() != "")
//    jQuery("#AlertsLocation3").css("display", "block");
//  if (jQuery("#AlertsLocation4").html() != "")
//    jQuery("#AlertsLocation4").css("display", "block");
//  if (jQuery("#AlertsLocation5").html() != "")
//    jQuery("#AlertsLocation5").css("display", "block");


  jQuery("#AlertSettings").css("display", "none");
  jQuery("#AlertsDiv").css("display", "block");
}

function AlertsDivClose() {
  jQuery("#AlertsDiv").css("display", "none");
  jQuery("#AlertSettings").css("display", "block");
}

function EmailToLocation() {
  if (!IsValidEmailAddress(jQuery("#AlertsEmailInput").val())) {
    alert("Please provide a valid e-mail address.");
    jQuery("#AlertsEmailInput").focus();
    return false;
  }
  else {
    jQuery("#AlertsEmail").css("display", "none");
    jQuery("#AlertsLocation").css("display", "block");
  }
}

function LocationToAlerts() {
  if (jQuery("#AlertsLocation1").html() == "") {
    alert("Please select a location.");
    jQuery("#AlertsLocationInput").focus();
    return false;
  }
  else {
    jQuery("#AlertsLocation").css("display", "none");
    jQuery("#AlertsTypes").css("display", "block");
  }
}

function LocationToEmail() {
  jQuery("#AlertsLocation").css("display", "none");
  jQuery("#AlertsEmail").css("display", "block");
}

function AlertsToLocation() {
  jQuery("#AlertsTypes").css("display", "none");
  jQuery("#AlertsLocation").css("display", "block");

  if (jQuery("#AlertsLocation5").html() != "") {
    jQuery("#AddLocationButton").attr("disabled", "disabled");
    jQuery("#LocationsMaxed").css("display", "block");
  }
}

function AddLocation() {
  if (jQuery("#AlertsLocation1").html() != "") {
    jQuery("#AlertsLocation1").css("display", "block");
    jQuery("#RemoveLocation1").css("display", "block");
  }
  if (jQuery("#AlertsLocation2").html() != "") {
    jQuery("#AlertsLocation2").css("display", "block");
    jQuery("#RemoveLocation2").css("display", "block");
  }
  if (jQuery("#AlertsLocation3").html() != "") {
    jQuery("#AlertsLocation3").css("display", "block");
    jQuery("#RemoveLocation3").css("display", "block");
  }
  if (jQuery("#AlertsLocation4").html() != "") {
    jQuery("#AlertsLocation4").css("display", "block");
    jQuery("#RemoveLocation4").css("display", "block");
  }
  if (jQuery("#AlertsLocation5").html() != "") {
    jQuery("#AlertsLocation5").css("display", "block");
    jQuery("#RemoveLocation5").css("display", "block");
    jQuery("#AddLocationButton").attr("disabled", "disabled");
    jQuery("#LocationsMaxed").css("display", "block");
  }

  jQuery("#AlertsLocationInput").val("Enter City, State, or U.S. Zip Code");
  jQuery("#AlertsLocationInput").css("font-size", "10px");
  jQuery("#AlertsLocationInput").css("color", "#999");
}

function RemoveLocation(locationDiv) {
  if (locationDiv == "AlertsLocation1") {
    jQuery("#AlertsLocation1").html("");
    jQuery("#AlertsLocation1CityId").html("");
    jQuery("#AlertsLocation1").css("display", "none");
    jQuery("#RemoveLocation1").css("display", "none");
  }
  if (locationDiv == "AlertsLocation2") {
    jQuery("#AlertsLocation2").html("");
    jQuery("#AlertsLocation2CityId").html("");
    jQuery("#AlertsLocation2").css("display", "none");
    jQuery("#RemoveLocation2").css("display", "none");
  }
  if (locationDiv == "AlertsLocation3") {
    jQuery("#AlertsLocation3").html("");
    jQuery("#AlertsLocation3CityId").html("");
    jQuery("#AlertsLocation3").css("display", "none");
    jQuery("#RemoveLocation3").css("display", "none");
  }
  if (locationDiv == "AlertsLocation4") {
    jQuery("#AlertsLocation4").html("");
    jQuery("#AlertsLocation4CityId").html("");
    jQuery("#AlertsLocation4").css("display", "none");
    jQuery("#RemoveLocation4").css("display", "none");
  }
  if (locationDiv == "AlertsLocation5") {
    jQuery("#AlertsLocation5").html("");
    jQuery("#AlertsLocation5CityId").html("");
    jQuery("#AlertsLocation5").css("display", "none");
    jQuery("#RemoveLocation5").css("display", "none");
  }

  jQuery("#AddLocationButton").attr("disabled", "");
  jQuery("#LocationsMaxed").css("display", "none");
}

function AlertsSubmit() {
  var email = jQuery("#AlertsEmailInput").val();
  var userid = jQuery("#UserIdHidden").html();
  var source = jQuery("#SourceHidden").html();
  
  var location = "";
  if (jQuery("#AlertsLocation1CityId").html() != "")
    location = location + "," + jQuery("#AlertsLocation1CityId").html();
  if (jQuery("#AlertsLocation2CityId").html() != "")
    location = location + "," + jQuery("#AlertsLocation2CityId").html();
  if (jQuery("#AlertsLocation3CityId").html() != "")
    location = location + "," + jQuery("#AlertsLocation3CityId").html();
  if (jQuery("#AlertsLocation4CityId").html() != "")
    location = location + "," + jQuery("#AlertsLocation4CityId").html();
  if (jQuery("#AlertsLocation5CityId").html() != "")
    location = location + "," + jQuery("#AlertsLocation5CityId").html();
  location = location.substring(1, location.length);

  var alertTypes = "";
  var hasCheckedAlertTypes = "";
  jQuery(':checkbox:not(:checked)').each(function (i) { alertTypes = alertTypes + "," + jQuery(this).val(); });
  jQuery(':checkbox:checked').each(function (i) { hasCheckedAlertTypes = hasCheckedAlertTypes + "," + jQuery(this).val(); });

  if (hasCheckedAlertTypes == "") {
    alert("Please select at least one alert type.");
    jQuery("#AlertsTypes").focus();
    return;
  }

  alertTypes = alertTypes.substring(1, alertTypes.length);

  MakeAjaxCallSaveAlertSettings('/Handlers/AlertEmail.js?method=update&userid=' + userid + '&source=' + source + '&email=' + email + '&location=' + location + '&alertTypes=' + alertTypes);
}

function AlertsUnsubscribe() {
  var userid = jQuery("#UserIdHidden").html();
  if (confirm("Are you sure you want to unsubscribe from Severe Weather Alert E-mail Notifications?"))
    MakeAjaxCallSaveAlertSettings('/Handlers/AlertEmail.js?method=unsubscribe&userid=' + userid);
}

function MakeAjaxCallSaveAlertSettings(url) {
  var request = getXMLHttpRequest();
  if (request != null) {
    request.open("GET", url, true);
    request.onreadystatechange = function () {
      if (request.readyState == 4 /* complete */) {
        if (request.status == 200) {
          location.reload(true);
          //window.open(request.responseText);
        }
      }
    };
    request.send();
  }
}


// Location Search Functions
function AlertLocation_Swipe(state) {
  var icast_text = "Enter City, State, or U.S. Zip Code";
  if (state == 'on' && jQuery("#AlertsLocationInput").val() == icast_text) {
    jQuery("#AlertsLocationInput").val(""); jQuery("#AlertsLocationInput").css("font-size", "11px"); jQuery("#AlertsLocationInput").css("color", "#454545");
  }
  else if (jQuery("#AlertsLocationInput").val() == "") {
    jQuery("#AlertsLocationInput").val(icast_text); jQuery("#AlertsLocationInput").css("font-size", "10px"); jQuery("#AlertsLocationInput").css("color", "#999");
  }
}

// Weather Alert Email AutoComplete
function icast_WxAlertEmailCitySearch() {
  jQuery(document).ready(function () {
    var host = "http://www.intellicast.com/Search.axd";
    jQuery("#AlertsLocationInput").autocomplete(host + "?filter=" + icast_SearchFilter, {
      dataType: 'jsonp',
      parse: function (data) {
        var rows = new Array();
        for (var i = 0; i < data.results.count; i++) {
          rows[i] = { data: data.results.locations.location[i], value: data.results.locations.location[i].name, result: data.results.locations.location[i].name };
        }
        return rows;
      },
      minChars: 3,
      formatItem: function (row, i, n) {
        return row.name
      }
    });

    jQuery("#AlertsLocationInput").result(function (event, data, formatted) {
      if (jQuery("#AlertsLocation1").html() == "") {
        jQuery("#AlertsLocation1").html(data.name);
        jQuery("#AlertsLocation1CityId").html(data.id);
      }
      else if (jQuery("#AlertsLocation2").html() == "") {
        jQuery("#AlertsLocation2").html(data.name);
        jQuery("#AlertsLocation2CityId").html(data.id);
      }
      else if (jQuery("#AlertsLocation3").html() == "") {
        jQuery("#AlertsLocation3").html(data.name);
        jQuery("#AlertsLocation3CityId").html(data.id);
      }
      else if (jQuery("#AlertsLocation4").html() == "") {
        jQuery("#AlertsLocation4").html(data.name);
        jQuery("#AlertsLocation4CityId").html(data.id);
      }
      else if (jQuery("#AlertsLocation5").html() == "") {
        jQuery("#AlertsLocation5").html(data.name);
        jQuery("#AlertsLocation5CityId").html(data.id);
      }

    });
  });
}



