var myArgs;
var myHpPath = "http://swf.yowindow.com/wimo/hpPal";
var myAutoUnitSystem;
var myLocation = null;
var myLandscape = null;
var myLocationName = null;
var myLocationPath = null;

var myTraceText = "";
var myIsPalReady = false;
var myIsChooserReady = false;

var myLinkName = "Link";
var myLinkUrl = "http://yowindow.com/online";

var addthis_config = {
    data_track_clickback: true
}

function getArgs() {
	if (!myArgs) {
		myArgs = parseArgs();
	}
	return myArgs;
}

function parseArgs() {
    var map = new Array();
    var s = "";
    try {
	    s = location.search.substring(1);
    }
    catch(e) {
    }

    var qString = unescape(s);
    var pairs = qString.split(/[&]/);
    for (var i in pairs) {
    	if (!pairs[i]) {
    		continue;
    	}
	    var pair = pairs[i].split(/\=/);
	    map[pair[0]] = pair[1];
    }
    return map;
}

function getLanguage() {
	var lang = getLanguageImpl();
	var usIndex = lang.indexOf('-');
	if (usIndex != -1) {
		var dialect = lang.substring(usIndex + 1);
		if (dialect == 'at') {
		}
		else {
			lang = lang.substring(0, usIndex);
		}
	}
	return lang;
}

function getLanguageImpl() {
	var lang = navigator.userLanguage;
	if (!lang) {
		lang = navigator.language;
	}
	if (!lang) {
		lang = navigator.browserLanguage;
	}
	return lang;
}

function updateHpLocationChooserSwf() {
    var flashvars = {
    };
    
    var params = {
    	quality: "high",
    	bgcolor: "#EEEEEE",
		allowscriptaccess: "always",
		allowfullscreen: "true",
		wmode: "transparent"
    };

    var attributes = {
    	id:"hpLocationChooser",
    	name:"hpLocationChooser"
    };

    swfobject.embedSWF(
    	myHpPath + "/hpLocationChooser.swf", 
    	"hpLocationChooser", 
    	"245",
    	"150", 
    	"9.0.0",
    	"expressInstall.swf",
    	flashvars,
    	params,
    	attributes
    );
}

function updatePalSwf() {
	var args = getArgs();
	args['background'] = "#FFFFFF";

    var flashvars = args;
//d		trace_text_area: "1",
	if (!flashvars['location_id']) {
		flashvars['location_auto_ip'] = 1;
	}

	var lang = getLanguage();
	flashvars['lang'] = lang;


    var params = {
    	quality: "high",
    	bgcolor: "#FFFFFF",
		allowscriptaccess: "always",
		allowfullscreen: "true",
		menu: "false",
		wmode: "window"
    };

    var attributes = {
    	id:"hpPal",
    	name:"hpPal"
    };

    swfobject.embedSWF(
    	myHpPath + "/hpPal.swf",
    	"hpPal", 
    	"760", 
    	"444",
    	"9.0.0",
    	"expressInstall.swf",
    	flashvars,
    	params,
    	attributes
    );
}

var local = false;

try {
	local = (location.href.indexOf("file://") == 0);
}
catch(e) {
}

if (local) {
	myHpPath = "http://localhost/wimo/hpPal";
}

var args = getArgs();
myLocation = args['location_id'];
myLocationName = args['ln'];

updatePalSwf();
updateHpLocationChooserSwf();

myLandscape = args['landscape'];


//p p("landscape=" + myLandscape);

function addToFavorites() { 
	addBookmark(myLinkUrl, myLinkName);
}

function addBookmark(url, title) {
    if (!url) url = location.href;
    if (!title) title = document.title;

    //Gecko
    if ((typeof window.sidebar == "object") && (typeof window.sidebar.addPanel == "function")) window.sidebar.addPanel (title, url, "");
    //IE4+
    else if (typeof window.external == "object") window.external.AddFavorite(url, title);
    //Opera7+
    else if (window.opera && document.createElement) {
      var a = document.createElement('A');
      if (!a) return false; //IF Opera 6
      a.setAttribute('rel','sidebar');
      a.setAttribute('href',url);
      a.setAttribute('title',title);
      a.click();
    }
    else return false;

    return true;
}


function hpPal_DoFSCommand(command, args) {
    if (command == "partrace") {
        p("[Pal] " + args);
    }
    else if (command == "readyForCommands") {
    	onPalReady();
    }
}

function hpLocationChooser_DoFSCommand(command, args) {
    if (command == "partrace") {
        p("[LC] " + args);
    }
    else if (command == "readyForCommands") {
    	onChooserReady();
    }
}

function onLoad() {	

	var tf = getArgs()['tf'];
	if (!tf) {
		tf = getAutoTimeFormat();
	}
	document.getElementById(tf == "24" ? 't24' : 't12').checked = true;


	var usId = getArgs()['us'];
	if (!usId) {
		usId = getAutoUnitSystemImpl();
	}

	var usItemId = 'temUnitF';
	if (usId == 'metric') {
		usItemId = 'temUnitC';
	}
/*o
	else if (usId == 'auto') {
		usItemId = 'temUnitAuto';
	}
*/
	document.getElementById(usItemId).checked = true;


	reflectTimeFormatInPal();
	reflectUnitSystemInPal();
	
	updateQueryString();


	var debug_box = document.getElementById('debug_box');
	debug_box.style.display = local ? 'block' : 'none';
    var traceArea = document.getElementById('traceArea');
    if (traceArea) {
    	traceArea.value = "";
    }
}

function onPalReady() {
//p("onPalReady()");

	myIsPalReady = true;

	reflectUnitSystemInPal();
	reflectTimeFormatInPal();	
}

function onChooserReady() {
//p	p("onLocationChooserReady()");
	myIsChooserReady = true;
	var chooser = document.getElementById('hpLocationChooser');
	chooser.setScope('allLocations');

	reflectLocationPathInChooser();
}

function selectLocation(locationId, name) {
	myLocation = locationId;
	myLocationPath = null;
	myLocationName = name;
	reflectLocationInPal();
	updateQueryString();
}

//---- LC
function hpHandleLocationDetected(locationId, path) {
//p	p("hpHandleLocationDetected");
	myLocation = locationId;
	myLocationPath = path;
	reflectLocationPathInChooser();
}

function hpHandleLocationSelected(id, name, path) {
//p p("hpHandleLocationSelected, id=" + id + ", name=" + name + ", path=" + path);
	myLocation = id;
	myLocationName = name;
	myLocationPath = path;

	updateQueryString();
	reflectLocationPathInChooser();
}


function handleLocationChange(locationId, name) {
//p	p("handleLocationChange(), locationId=" + locationId + ", name=" + name);
	if (myLocation == locationId) {
		return;
	}
    
    try {//.required in external methods, because exception here is silent for js-error console
//.No location selected in location-chooser, do not change selected location.
    	if (!locationId) {
    		return;
    	}
    	myLocation = locationId;
    	myLocationName = name;
		updateQueryString();
		reflectLocationInPal();
    }
    catch (e) {
//d    	
		alert("handleLocationChange(), exception: " + e);
    }
}

function requestUiTop() {
try {
//p	p("requestUiTop()");
	var layer = document.getElementById('locationChooserLayer');
	if (layer.style.zIndex == 4) {
		severe("unexpected layer zIndex value, v=" + layer.style.zIndex);
	}
	layer.style.zIndex = 4;
//p	p("layer=" + layer);
//	
	var hpLocationChooser = window.document.getElementById('hpLocationChooser');
//p	p("hpLocationChooser=" + hpLocationChooser);
//no		hpLocationChooser.width = 1000;
		hpLocationChooser.height = 300;
    }
    catch (e) {
    	alert("requestUiTop(), exception: " + e);
    }
}

function releaseUiTop() {
//p	p("releaseUiTop()");
try {
	var layer = document.getElementById('locationChooserLayer');
	if (layer.style.zIndex != 4) {
		severe("unexpected layer zIndex value");
	}
	layer.style.zIndex = 2;
    }
catch (e) {
	alert("releaseUiTop(), exception: " + e);
}

}
//External interface >

function reflectLocationInPal() {
	if (!myLocation) {
		return;
	}
	var pal = document.getElementById('hpPal');

	if (!myIsPalReady) {
		return;
	}
	if (!pal) {
		severe("pal is missing at reflectLocationInPal()");
		return;
	}
//p	p("setLocation(), myLocation="+myLocation+"\n");
	pal.setLocationId(myLocation);
	pal.setLandscapeUrl(null);
}

function reflectLocationPathInChooser() {
//p	p("reflectLocationPathInChooser(), myLocationPath=" + myLocationPath + ", myIsChooserReady=" + myIsChooserReady);
	if (!myLocationPath) {
		return;
	}
	if (!myIsChooserReady) {
		return;
	}
	var chooser = document.getElementById('hpLocationChooser');
	chooser.setPath(myLocationPath);
}

function reflectTimeFormatInPal() {
	if (!myIsPalReady) {
		return;
	}
	var pal = document.getElementById('hpPal');
	var timeFormat = getTimeFormat();
	if (timeFormat != "") {
		pal.setSimpleTimeFormat(timeFormat);
	}
}

function reflectUnitSystemInPal() {
	if (!myIsPalReady) {
		return;
	}
	var id = getUnitSystemId();
	if (id == "") {
		id = getAutoUnitSystem();
	}
	var pal = document.getElementById('hpPal');
	pal.setUnitSystem(id);
}

function selectLocationAndLandscape(locationId, url) {
	var pal = document.getElementById('hpPal');
//p p("selectLocationAndLandscape(), locaitonId=" + locationId);
	myLocation = locationId;
	myLandscape = url;

	pal.setLocationId(locationId);
	pal.setLandscapeUrl(url);

	updateQueryString();
}

function getTimeFormat() {
	if (document.getElementById('t24').checked) {
		return "24";
	}
	return "12";
}

function handleTimeFormatChange() {	
	reflectTimeFormatInPal();
	updateQueryString();
}

function getUnitSystemId() {
	if (document.getElementById('temUnitC').checked) {
		return "metric";
	}
/*o
	else if (document.getElementById('temUnitAuto').checked) {
		return "";
	}
*/
	return "us";
}

function handleTemUnitChange() {
	reflectUnitSystemInPal();
	updateQueryString();
}

function updateQueryString() {
	var name = "YoWindow";
	if (myLocationName) {
		name = myLocationName;
	}

    var qString = "";
    try {
    	qString = unescape(location.search.substring(1));
    }
    catch(e) {
    }
    var pairs = [];
    var map = {};

    if (qString) {
        qString.split(/\&/);
        for (var i in pairs) {
    	    var pair = pairs[i].split(/\=/);
    	    map[pair[0]] = pair;
        }
	}
	
	if (myLocation) {
    	addPair(pairs, map, 'location_id', myLocation);
	}
	if (myLocationName) {
		addPair(pairs, map, 'ln', myLocationName);
	}

	var tf = getTimeFormat();
	addPair(pairs, map, "tf", tf);

	var us = getUnitSystemId();
	addPair(pairs, map, "us", us);

	var hostname = "";
	var index = -1;
	try {
		hostname = location;
		index = location.href.indexOf("?");
    	if (index != -1) {
    		hostname = top.location.href.substring(0, index);
    	}
	}
	catch(e) {
	}

	if (myLandscape) {
    	addPair(pairs, map, 'landscape', myLandscape);
	}

    var text = "";
    for (var i in pairs) {
	    var pair = pairs[i];
	    if (text) {
	    	text += "&";
	    }
//p	    p("p0=" + pair[0]);
		if (pair[1] != null) {
	    	text += pair[0] + "=" + pair[1];
	    }
    }

    if (text) {
    	text = hostname + "?" + text;
    }
    else {
    	text = hostname;
    }

    var link_input = document.getElementById('link_input');
    if (link_input) {
    	link_input.value = text;
    }

    var link_name = document.getElementById('link_name');
    link_name.innerHTML = name;
    var link1 = document.getElementById('link1');
    link1.href = text;
    link1.title = name + " Weather Channel";
    link1.alt = name + " Weather Channel";

    myLinkUrl = text;
    myLinkName = name;
}

function link_select_all() {
    var link_input = document.getElementById('link_input');
	link_input.focus();
	link_input.select();
}

function addPair(pairs, map, key, value) {
	if (value == null || value == "") {
		return;
	}
	var pair = map[key];
	if (!pair) {
		pair = new Array(key, "");
		map[key] = pair;
		pairs.push(pair);
	}
   	pair[1] = value;
}

function getAutoUnitSystem() {
	if (!myAutoUnitSystem) {
		myAutoUnitSystem= getAutoUnitSystemImpl();
	}
	return myAutoUnitSystem;
}

function getAutoUnitSystemImpl() {
    var date = new Date(77, 11 - 1, 5, 20, 00);
    var s = date.toLocaleString();
//p    p("date.localeString()=" + s);    
//t    document.getElementById("broken").value = "a";
    if (s.indexOf("®пЎа") != -1) {
        return "russian";
    }

    if (s.lastIndexOf("PM") == (s.length - 2)) {
        return "us";
    }
    return "metric";
}

function getAutoTimeFormat() {
    var date = new Date(77, 11 - 1, 5, 20, 00);
    var s = date.toLocaleString();
    if (s.lastIndexOf("PM") == (s.length - 2) || s.indexOf("8:00") != -1) {
        return "12";
    }
    return "24";
}

function p(text) {
    myTraceText += text + "\n";
    var traceArea = document.getElementById('traceArea');
    if (traceArea) {
    	traceArea.value = myTraceText;
    }
}

function severe(text) {
	p("[SEVERE] " + text);
}
