﻿    var MIN_WIDTH = 120;
    var MAX_WIDTH = 800;
    var MIN_HEIGHT = 50;
    var MAX_HEIGHT = 500;

    var ID_US = 6252001;

    var myLocationId = null;
    var myLocationName = null;
    var myCountryId = null;
    var myLocationPath = null;

    var myPalWidth = 
    280
    //380
    ;
    var myPalHeight = 
    194
    //200
    ;
    var myAutoUnitSystem;
    var myTraceText = "";
    var myIsPalReady = false;
    var myIsChooserReady = false;
     
    var myHpPalFlashVars;

    var myIsLocal = (location.href.indexOf("file://") == 0);

    function onLoad() {
    	var cb = document.getElementById('language_cb');
    	var lang = getLanguage();
//p    	p("lang=" + lang);
    	selectOptionByValue(cb, lang);


    	var us = getAutoUnitSystem();
    //p	p("us=" + us);
    	if (us == 'us') {
    		document.getElementById('temUnitF').checked = true;
    	}
    	else if (us == 'metric') {
    		document.getElementById('temUnitC').checked = true;
    	}
    	else {
    		document.getElementById('temUnitAuto').checked = true;
    	}

    	var tf = getAutoTimeFormat();
    //p	p("tf=" + tf);
    	if (tf == '24') {
    		document.getElementById('t24').checked = true;
    	}
    	else {
    		document.getElementById('t12').checked = true;
    	}

    	updatePalSwf();
    	updateHpLocationChooserSwf();
    	update();

    //o    document.getElementById('hpPal').focus();
    //WARNING: sometimes throws, not-found exception   document.getElementById('hpLocationChooser').focus();
    	document.getElementById('width_tf').value = myPalWidth;
    	document.getElementById('height_tf').value = myPalHeight;

    	document.getElementById('mini_temperature').checked = true;
    	document.getElementById('mini_time').checked = true;
    	document.getElementById('mini_locationBar').checked = true;
    	document.getElementById('mini_momentBar').checked = true;

    	var debug_box = document.getElementById('debug_box');
    	debug_box.style.display = myIsLocal ? 'block' : 'none';

        var traceWindow = document.getElementById('traceWindow');
        if (traceWindow) {
        	traceWindow.value = "";
        }
    }

    function updatePalSwf() {
    	var cb = document.getElementById('language_cb');
    	var lang = cb.value;

        var flashvars = {
    		location_auto_ip: 1,
    //o		location_id: "gn:5128581",
    		background: "#FFFFFF",
    		role: "setup",
    //d		mini_change_button: true,
    		time_format: "12",
    		lang: lang,
    		copyright_bar: "false"
    //d		trace_text_area: "1",
        };

        if (myIsLocal) {
//d	flashvars['landscape_url'] = "img/landscape_test1.jpg";
        }

        myHpPalFlashVars = flashvars;

        var params = {
        	quality: "high",
        	bgcolor: "#FFFFFF",
    		allowscriptaccess: "always",
    		allowfullscreen: "true",
			menu: "false"
        };

        var attributes = {
        	id:"hpPal",
        	name:"hpPal"
        };

        var url = "http://swf.yowindow.com/wimo/hpPal/hpPal.swf";
        if (myIsLocal) {
//        	url = "http://127.0.0.1:8081/wimo/hpPal/hpPal.swf"
//o
			url = "http://localhost/wimo/hpPal/hpPal.swf";
			
        }


        swfobject.embedSWF(
        	url, 
        	"hpPal", 
        	"280", 
        	"194",
        	"9.0.0",
        	"expressInstall.swf",
        	flashvars,
        	params,
        	attributes
        );

        updatePalSize();
    }

    function updateHpLocationChooserSwf() {
        var flashvars = {
        };
        
        var params = {
        	quality: "high",
        	bgcolor: "#EEEEEE",
    		allowscriptaccess: "always",
    		allowfullscreen: "true",
    		wmode: "transparent",
			menu: "false"
        };

        var attributes = {
        	id:"hpLocationChooser",
        	name:"hpLocationChooser"
        };

        var url = "http://swf.yowindow.com/wimo/hpPal/hpLocationChooser.swf";
        if (myIsLocal) {
    	    url = "http://localhost/wimo/hpPal/hpLocationChooser.swf";
        }

        swfobject.embedSWF(
        	url, 
        	"hpLocationChooser", 
        	"250", 
        	"150", 
        	"9.0.0",
        	"expressInstall.swf",
        	flashvars,
        	params,
        	attributes
        );
    }

    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 updateHtmlCode() {
    	var codeHtml = formatHtmlCode();
    //p	alert("updateHtmlCode(), code...\n" + (codeHtml != null));
        document.getElementById('htmlCode').value = codeHtml;
    //p   p("html=" + codeHtml + ", myspace=" + myspace);
    }

    function formatHtmlCode() {
    //p	p("formatHtmlCode(), myLocation=" + myLocation);
    	if (!myLocationId) {
    		return null;
    	}

    	var background = "#FFFFFF";
    	
    	var flashvars = 'location_id=' + myLocationId;

    	if (myLocationName) {
    		flashvars += '&amp;location_name=' + encodeURI(myLocationName);
    	}
    	
    	var timeFormat = getTimeFormat();
    	if (timeFormat != "") {
    		flashvars += '&amp;time_format=' + timeFormat;
    	}

    	var usId = getUnitSystemId();
    	if (usId == "") {
    		usId = getAutoUnitSystem();
    	}
    	if (usId != "") {
    		flashvars += '&amp;unit_system=' + usId;
    	}

    	var cb = document.getElementById('language_cb');
    	var lang = cb.value;
    	if (lang != "" && lang != 'en') {
    		flashvars += '&amp;lang=' + lang;
    	}

    	flashvars += '&amp;background=' + background;
    	
    	flashvars += formatFlashVarForViewProperty('mini_temperature');
    	flashvars += formatFlashVarForViewProperty('mini_time');
    	flashvars += formatFlashVarForViewProperty('mini_locationBar');
    	flashvars += formatFlashVarForViewProperty('mini_momentBar');
    	flashvars += '&amp;copyright_bar=false';
    //d	flashvars += "&trace_text_area=1";

    	var width = myPalWidth;
    	var height = myPalHeight;
    	var url = "http://swf.yowindow.com/wimo/hpPal/hpPal.swf";


    	var titles = [
    		"Weather Widget",
    		"Weather Widget",
    		"Weather Widget",
    		"Weather Widget",
    		"Free Weather Widget",
    		"Free Weather Widget",
    		"Free Weather Widget",
    		"Free Weather Widget",
    		"Free Weather Widget",
    		"Weather screensaver",
    		"Weather screensavers",
    		"Free Weather Widget",
    		"Free Desktop weather",
    		"Desktop temperature",
    		"Desktop temperature",
    		"Desktop temperature",
    		"Desktop temperature",
    		"Desktop temperature",
    		"Desktop weather",
    		"Weather forecast",
    		"Weather software",
    		"Windows weather",
    		"YoWindow",
    		"Weather for blog",
    		"Weather gadget",
    		"Blogger weather",
    		"MySpace weather",
    		"Weather station"
    	];

    	var rnd = Math.random();
    	var index = Math.floor(rnd * titles.length);
		var title1 = titles[index];

    	rnd = Math.random();
    	index = Math.floor(rnd * titles.length);
		title2 = titles[index];
/*


*/

		var yrnoCopyrightHtml = formatProviderCopyrightHtml();

    	var text = '\
<div style="width:' + width + 'px; height:' + height + 'px;">\n\
    <object type="application/x-shockwave-flash" data="' + url + '" width="' + width + '" height="' + height + '">\n\
    	<param name="movie" value="' + url + '"/>\n\
    	<param name="allowfullscreen" value="true"/>\n\
    	<param name="wmode" value="opaque"/>\n\
    	<param name="bgcolor" value="' + background + '"/>\n\
    	<param name="flashvars" \n\
    	value="' + flashvars + '"\n\
    />\n\
        <a href="http://yowindow.com?client=widget&amp;link=stub"\n\
        style="width:' + width + 'px;height:' + height + 'px;display: block;text-indent: -50000px;font-size: 0px;-moz-background-clip:border;-moz-background-inline-policy:continuous;-moz-background-origin:padding;background:#DDF url(http://yowindow.com/img/logo.png) no-repeat scroll 50% 50%;"\n\
        >' + title1 + '</a>\n\
    </object>\n\
</div>\n\
<div style="width: ' + width + 'px; height: 15px; font-size: 12px; font-family: Arial,Helvetica,sans-serif;">\n\
	<span style="float:left;"><a target="_top" href="http://yowindow.com?client=widget&amp;link=copyright" style="color: #2fa900; text-decoration:none;" title="' + title2 + '">YoWindow.com</a></span>\n\
	<span style="float:right; color:#888888;">' 
	+ yrnoCopyrightHtml
	+ '</span>\n\
</div>\n\
';
    	return text;
    }

    function html_select_all() {
		var c = document.getElementById('htmlCode');
		c.focus();
		c.select();
    }

    function formatFlashVarForViewProperty(id) {
    	var value = myHpPalFlashVars[id];
    	if (value == null) {
    		return "";
    	}
    	return '&amp;' + id + '=' + value;
    }

    function reflectTimeFormatInPal() {
    	var pal = document.getElementById('hpPal');
    	var timeFormat = getTimeFormat();
    	if (timeFormat != "") {
    		pal.setSimpleTimeFormat(timeFormat);
    	}
    }

    function reflectUnitSystemInPal() {
    	var id = getUnitSystemId();
    	if (id == "") {
    		id = getAutoUnitSystem();
    	}
    	var pal = document.getElementById('hpPal');
    	pal.setUnitSystem(id);
    }

    function reflectLocationInPal() {
    	if (!myLocationId) {
    		return;
    	}
    	var pal = document.getElementById('hpPal');

    	if (!myIsPalReady) {
    		return;
    	}
    	if (!pal) {
    		severe("pal is missing at reflectLocationInPal()");
    		return;
    	}
    	if (myLocationId) {
    		pal.setLocationId(myLocationId);
    	}
    	pal.setLocationName(myLocationName);
    }

    function reflectLocationPathInChooser() {
//p	p("reflectLocationPathInChooser(), myLocationPath=" + myLocationPath + ", myIsChooserReady=" + myIsChooserReady);
    	if (!myLocationPath) {
    		return;
    	}
    	if (!myIsChooserReady) {
    		return;
    	}
    	var chooser = document.getElementById('hpLocationChooser');
    	chooser.setPath(myLocationPath);
    }

    function selectLocationAndLandscape(locationId, url) {
		var pal = document.getElementById('hpPal');
    	myLocationId = locationId;

    	pal.setLocationId(locationId);
    	pal.setLandscapeUrl(url);
    }

    function validateWidth() {	
    	var tag = document.getElementById('width_tf');
    	var width = tag.value;
    	var result = parseWidth(width);
    	var ok = result && result.correct;
    	tag.className = ok ? "normal" : "fieldError";
    	if (ok) {
    		myPalWidth = result.value;
    		update();
    	}
    }

    function validateHeight() {	
    	var tag = document.getElementById('height_tf');
    	var height = tag.value;
    	var result = parseHeight(height);
    	var ok = result && result.correct;
    	tag.className = ok ? "normal" : "fieldError";
    	if (ok) {
    		myPalHeight = result.value;
    		update();
    	}
    }

    function parseWidth(value) {
    	if (!value.match("^[0-9]*$")) {
    		return null;
    	}
    	var correct = true;
    	if (value < MIN_WIDTH) {
    		value = MIN_WIDTH;
    		correct = false;
    	}
    	if (value > MAX_WIDTH) {
    		value = MAX_WIDTH;
    		correct = false;
    	}
    	return {
    		correct: correct,
    		value: value
    	}
    }

    function parseHeight(value) {
    	if (!value.match("^[0-9]*$")) {
    		return null;
    	}
    	var correct = true;
    	if (value < MIN_HEIGHT) {
    		value = MIN_HEIGHT;
    		correct = false;
    	}
    	if (value > MAX_HEIGHT) {
    		value = MAX_HEIGHT;
    		correct = false;
    	}
    	return {
    		correct: correct,
    		value: value
    	}
    }

    function update() {	
    	updateHtmlCode();
    	updatePalSize();
    }

    function updatePalSize() {
    	var pal = document.getElementById('hpPal');

    	pal.width = myPalWidth;
    	pal.height = myPalHeight;

    	var container = document.getElementById('hpPalContainer');
		container.style.width = myPalWidth + "px";
		container.style.height = myPalHeight + "px";

		var bar = document.getElementById('copyrightBar');
		bar.style.width = myPalWidth + "px";
		
		updateProviderHtml();
    }

    function updateProviderHtml() {
		var provider = document.getElementById('providerCopyright');
		provider.innerHTML = formatProviderCopyrightHtml(myPalWidth);
    }

    function formatProviderCopyrightHtml() {
		var gap = 5;
		var yowindowWidth = 112;
		var givenWidth = myPalWidth - (yowindowWidth + gap);
		
		var middleWidth = 62;

		var style = "color: #2fa900; text-decoration:none;";
		var url = "http://yr.no";
		var name = "yr.no";


        var isUs = myCountryId == ID_US;

        var isNws = isUs;
		if (isNws) {
			url = "http://www.weather.gov";
			name = "NWS";
		}

		var middleHtml = "Forecast by&nbsp;<a href=\"" + url + "\" style=\"" + style + "\">" + name + "</a>";
		var littleHtml = "<a href=\"" + url + "\" style=\"" + style + "\">" + name + "</a>";
		var html = middleHtml;
		if (givenWidth < middleWidth + gap) {
			html = littleHtml;
		}
		return html;
    }


    function handleLanguageChange() {
    //p	print ("handleLanguageChange()");
    	var cb = document.getElementById('language_cb');
    	updatePalSwf();
    	updateHtmlCode();
    }

    function handleLocationNameChange() {
    	var tf = document.getElementById('location_name_tf');
    	var name = 	tf.value;
    //p	p("name=" + name);
    	myLocationName = name;

    	var pal = document.getElementById('hpPal');
    	if (pal) {
    		pal.setLocationName(name);
    	}
       	updateHtmlCode();
    }

    function getTimeFormat() {
    	if (document.getElementById('t24').checked) {
    		return "24";
    	}
    	return "12";
    }

    function handleTimeFormatChange() {	
    	reflectTimeFormatInPal();	
    	updateHtmlCode();
    }

    function getUnitSystemId() {
    	if (document.getElementById('temUnitC').checked) {
    		return "metric";
    	}
    	else if (document.getElementById('temUnitAuto').checked) {
    		return "";
    	}
    	return "us";
    }

    function handleTemUnitChange() {
    	reflectUnitSystemInPal();
    	
    	updateHtmlCode();
    }

    function handleViewPropertyChange(id) {
    	var pal = document.getElementById('hpPal');
    	var b = document.getElementById(id).checked;
    	pal.setViewProperty(id, b);
    	myHpPalFlashVars[id] = b;
    	updateHtmlCode();
    }


    function testClick() {
    	var layer = document.getElementById('locationChooserLayer');
    	p("layer=" + layer + ", z-index=" + layer.style.zIndex);
    	layer.style.zIndex = 5;

    }

//External interface <
//---- Pal
    function unitSystem() {
    	return getUnitSystemId();
    }

    function hpHandleLocationDetected(locationId, path) {
    	myLocationId = locationId;
    	myLocationPath = path;
    	reflectLocationPathInChooser();
    }

    /*o
    function handleChangeButtonPress() {
    	p("handleChangeButtonPress()");
    }
    */

//---- LC
    function handleLocationChange(locationId, name, countryId) {
        try {//.required in external methods, because exception here is silent for js-error console
    //p	p("LC.handleLocationChange(), locationId=" + locationId + ", name=" + name);
    //.No location selected in location-chooser, do not change selected location.
        	if (!locationId) {
        		return;
        	}

        	myLocationId = locationId;
        	myCountryId = countryId;
        	reflectLocationInPal();

    		var location_name_tf = document.getElementById('location_name_tf');
    		location_name_tf.value = name;

    		updateProviderHtml();

        	updateHtmlCode();
        }
        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 = document.getElementById('hpLocationChooser');
        //p	p("hpLocationChooser=" + hpLocationChooser);
        //no		hpLocationChooser.width = 1000;
        //o
        	hpLocationChooser.height = 340;
        }
        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 p(text) {
        myTraceText += text + "\n";
        var traceWindow = document.getElementById('traceWindow');
        if (traceWindow) {
        	traceWindow.value = myTraceText;
        }
    }

    function severe(text) {
    	p("[SEVERE] " + text);
    }

    function onPalReady() {
    	myIsPalReady = true;
    	if (myLocationId) {
    		reflectLocationInPal();
    	}
        reflectTimeFormatInPal();
        reflectUnitSystemInPal();
    }


    function onChooserReady() {
//p	p("onChooserReady");
    	myIsChooserReady = true;

    	var chooser = document.getElementById('hpLocationChooser');
    	chooser.setScope('allLocations');

    	reflectLocationPathInChooser();
    }

    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);    
        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.indexOf("8:00") != -1) {
            return "12";
        }
        return "24";
    }

    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 selectOptionByValue(selObj, value) {
    	var options = selObj.options;
        for (var i = 0; i < options.length; i++) {
        	var item = options[i];
            if (item.value == value) {
                item.selected = true;
                break;
            }
        }  
    }

