// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

function include_dom(script_filename)
{
	var html_doc = document.getElementsByTagName('head').item(0);
	var js = document.createElement('script');
	js.setAttribute('language', 'javascript');
	js.setAttribute('type', 'text/javascript');
	js.setAttribute('src', script_filename);
	html_doc.appendChild(js);
	return false;
}

// Trim functions off the web...
// Removes leading whitespaces
function trimLeft(value) { return value.replace(/\s*((\S+\s*)*)/, "$1"); }

// Removes ending whitespaces
function trimRight(value) { return value.replace(/((\s*\S+)*)\s*/, "$1"); }

// Removes leading and ending whitespaces
function trim(value) { return trimLeft(trimRight(value)); }

function startsWith(startStr, sourceStr)
{
	if (sourceStr.indexOf(startStr) == 0) { return true; }
	return false;
}

function parseCurrentURL()
{
        docURL = document.URL.replace("http://", "");
        docURL = docURL.replace(new RegExp("/+", "g"), " ");
        docURL = trim(docURL);
        elements = docURL.split(" ");

        return elements;
}

function createSearchURL(query_string)
{ return createFormatURL("search_for-" + query_string, true, true); }

// The live search format doesn't include the query, it's is packaged with
// the ipr_search variable available via @params['ipr_search'] in rails
function createLiveSearchURL()
{
	return createFormatURL("live-search", false, false);
}

// Function takes the option of removing a subdomain.
// The subdomain is always ignored during searches but we remove it here
// for the URL look.  We don't always remove it because ajax requests seem
// to fail when removing the subdomain, I havent located why yet.
function createFormatURL(format_string, removeSubDomain, formatOnly)
{
        var elements = parseCurrentURL();

	// This is basically an error, return the current URL
        if (elements.length <= 0) { return document.URL; }

	var formatURL = createHostURL(elements, removeSubDomain);
	var newElements = new Array();
	if (elements.length > 1)
	{
		for(i = 1; i < elements.length; i++)
		{
			if (!formatOnly && elements[i].indexOf("_page-") >= 0)
			{ formatURL += "/" + elements[i]; }
			else
			{ newElements.push(elements[i]); }
		}
	}

        if (newElements.length == 0 || formatOnly)
	{ formatURL += "/group~/" + format_string; }
	else if (newElements.length == 1 || newElements.length == 2)
	{ formatURL += "/" + newElements[0] + "/" + format_string; }
        else if (newElements.length > 2)
	{
		formatURL += "/" + newElements[1] + "/" + format_string;
		for(i = 2; i < newElements.length; i++) { formatURL += "/" + newElements[i]; }
	}

        return formatURL;
}

function createHostURL(elementsURL, removeSubDomain)
{
        if (elementsURL.length <= 0) { return document.URL; }

	// Determine the host name, remove any subdomain
        host = elementsURL[0];
        host_elements = host.split(".");
        if (host_elements.length > 2 && removeSubDomain) { host = host_elements[1] + "." + host_elements[2]; }

        return "http://" + host;
}

function buildFormPostString(formName)
{
        formStr = "";

        elements = document.getElementById(formName).elements;
        for (i = 0; i < elements.length; i++)
        {
                if (formStr != "") { formStr += "&"; }
                formStr += elements[i].name + "=" + escape(elements[i].value);
        }

        return formStr;
}

function isolateFormName(element_id)
{
        validForms = ['pr_form', 'group_form', 'login_form'];
        for (i = 0; i < validForms.length; i++) { if (startsWith(validForms[i], element_id)) { return validForms[i]; } }
        return 
}

function updateFormEvent(eventObj) { updateFormData(isolateFormName(this.id), this.id); }

function updateFormData(formName, triggerElementID)
{
        formParamStr = buildFormPostString(formName);
        ajaxParamStr = 'ajax_request=true&trigger_element=' + triggerElementID;
        paramStr = ajaxParamStr + '&' + formParamStr;

        new Ajax.Updater
        ('dynamicContent', document.URL, {asynchronous:true, evalScripts:true, parameters:paramStr});
}

function updateLiveSearch(element, value)
{
        new Ajax.Updater
        (
                'dynamicContent', createLiveSearchURL(),
                {
                        asynchronous:true, evalScripts:true,
                        onComplete:function(request){Element.hide('busy_icon')},
                        onLoading:function(request){Element.show('busy_icon')},
                        parameters:'ipr_search=' + value
                }
        );
}

function updateAdminSiteMapBuild()
{
        new Ajax.Updater
        (
                'dynamicContent', createFormatURL('site-maps', false, false),
                {
                        asynchronous:true, evalScripts:true,
                        onComplete:function(request){Element.hide('busy_icon')},
                        onLoading:function(request){Element.show('busy_icon')},
                        parameters:'site_map_build_update=true'
                }
        );
}

function keyPressGetCharacterCode(eventObj)
{
        //Mozilla supports .which propetery, ELSE use IE style
        if(eventObj && eventObj.which) { return eventObj.which; }
        else { return event.keyCode; }
}

function keyPressIsReturn(eventObj)
{
        if (keyPressGetCharacterCode(eventObj) == 13) { return true; }
        return false;
}

function keyPressIsBackspace(eventObj)
{
        if (keyPressGetCharacterCode(eventObj) == 8) { return true; }
        return false;
}

function handleKeyPress(eventObj)
{
	switch (this.id)
        {
		case "gmap_search":
		case "ipr_search":
			field_value = trim(this.value);

			if (keyPressIsBackspace(eventObj))
			{ if (field_value == "") { window.location.reload(); } }

			if (keyPressIsReturn(eventObj))
			{
				if (field_value != "") { window.location = createSearchURL(field_value); }
				else { window.location = createHostURL(parseCurrentURL(), true); }
			}
			break;
		case "login_password":
			if (keyPressIsReturn(eventObj)) { document.login_form.submit(); }
			break;
	}
}

function registerKeyPressListener(elementID, handlerFunc)
{
	element = document.getElementById(elementID);

	if (navigator.appName != "Mozilla") { element.onkeyup = handlerFunc; }
	else { element.addEventListener("keypress", handlerFunc, true); }
}

function initializeForm(formName)
{
        switch (formName)
        {
                case "ipr_search":
                        new Form.Element.Observer('ipr_search', 1.75, updateLiveSearch, 'changed');
			registerKeyPressListener('ipr_search', handleKeyPress);
                        break;
                case "login_form":
                        document.getElementById('login_user_name').focus();
			registerKeyPressListener('login_password', handleKeyPress);
                        break;
                case "pr_form":
                        document.getElementById('pr_form_group_id').addEventListener('blur', updateFormEvent, true);
			document.getElementById('pr_form_headline').addEventListener('blur', updateFormEvent, true);
                        break;
		case "group_form":
			document.getElementById('group_form_country').addEventListener('blur', updateFormEvent, true);
                        break;
		case "gmap_search":
                        new Form.Element.Observer('gmap_search', 0.25, beginGmapLiveSearchTimer, 'changed');
                        registerKeyPressListener('gmap_search', handleKeyPress);
                        break;
        }
}

function pressReleasePreview(action_url)
{
	document.pr_form.target = "_blank";
	document.pr_form.action = action_url;
	document.pr_form.submit();
}

function pressReleaseSubmit()
{
	document.pr_form.target = '';
        document.pr_form.action = document.URL;
        document.pr_form.submit();
}

function fileUploadSubmit()
{
        document.upload_form.action = document.URL;
        document.upload_form.submit();
}

function beginAdminSiteMapBuild()
{
	//for (i = 0; i < 5; i++)
	//{
		updateAdminSiteMapBuild();
	//}
}

function fadeElement(elementID, fadeOut)
{
	fadeTime = 500;
	fadeSteps = 5;
	fadeTarget = 1.0;
	if (fadeOut) { fadeTarget = 0.0; }

	new Rico.Effect.FadeTo(elementID, fadeTarget, fadeTime, fadeSteps);
}

function fadeElementOut(elementID) { fadeElement(elementID, true); }
function fadeElementIn(elementID) { fadeElement(elementID, false); }

function beginPressReleaseSummaryUpdate()
{
	delay = 2750;
	//self.setTimeout("fadeElementOut('dynamicPressReleaseSummary');", delay);
	setTimeout("pressReleaseSummaryUpdate();", delay);
	setTimeout("fadeElementIn('dynamicPressReleaseSummary');", delay + 200);
	//pressReleaseSummaryUpdate();
}

function pressReleaseSummaryUpdate()
{
	divID = 'dynamicPressReleaseSummary';
	fadeElementOut(divID);

	//new Rico.Effect.FadeTo(divID,0,2000,10,{complete:function(){alert('Done');}})
	//alert(createFormatURL('press-release-random-summary', true, false));

	//alert("Update");
	//fadeElementOut(divID);

	new Ajax.Updater
        (
                divID, createFormatURL('press-release-random-summary', true, false),
                {
                        asynchronous:true, evalScripts:true,
                        parameters:'press_release_update=true'
                }
        );

	//self.setTimeout("fadeElementIn();", 1000);
	//fadeElementIn(divID);
	//document.getElementById('dynamicPressReleaseSummary').innerHTML = 'Check it'
}

// Currently the load function just creates some rounded box effects via Rico
function bodyOnLoad(use_google_map)
{
   	new Rico.Effect.Round( 'div', 'ricoRoundedBoxBottom', {corners:'bottom'} );
	new Rico.Effect.Round( 'div', 'ricoRoundedBoxTop', {corners:'top'} );
	new Rico.Effect.Round( 'div', 'ricoRoundedBox');

	// Call this function that should be defined in the head section for appropriate pages.
	if (use_google_map)
	{
		loadGMap();
		googleMapZoom('world');
	}
}

function googleMapZoom(zoom_mode)
{
	if (!window.googleMapObject) { return; }

	switch (zoom_mode)
	{
		case 'world':
                        window.googleMapObject.setCenter(new GLatLng(33.870278,-117.924444), 1);
			setGmapLocationStatus("The World");
                        break;

		case 'us':
			window.googleMapObject.setCenter(new GLatLng(40,-90), 3);
			setGmapLocationStatus("United States");
			break;

		case 'us_west':
			window.googleMapObject.setCenter(new GLatLng(41,-109), 4);
			setGmapLocationStatus("United States - West");
			break;

		case 'us_east':
			window.googleMapObject.setCenter(new GLatLng(38,-80), 4);
			setGmapLocationStatus("United States - East");
			break;

		case 'europe':
			window.googleMapObject.setCenter(new GLatLng(54, 25), 3);
			setGmapLocationStatus("Europe");
			break;

		case 'australia':
			window.googleMapObject.setCenter(new GLatLng(-28, 140), 3);
			setGmapLocationStatus("Australia / New Zealand");
			break;
	}
}

function beginGmapLiveSearchTimer(element, value)
{
        if (window.gmapLiveSearchTimer) { window.clearTimeout(window.gmapLiveSearchTimer); }
        window.gmapLiveSearchValue = value;
        window.gmapLiveSearchTimer = window.setTimeout(updateGmapLiveSearch, 1100);
}

function updateGmapLiveSearch()
{
        if (!window.googleMapObject) { return; }

        Element.show('gmap_busy_icon');
        setGmapLocationStatus("Searching...");
        var geocoder = new GClientGeocoder();

        geocoder.getLocations(window.gmapLiveSearchValue, handleGmapLiveSearchResults);
}

function handleGmapLiveSearchResults(response)
{
        setGmapLocationStatus("");
        Element.hide('gmap_busy_icon');

        if (!response || response.Status.code != 200)
        {
                googleMapZoom('world');
                setGmapLocationStatus("[unknown location]");
                return;
        }

        var placeMark = response.Placemark[0];
        if (!placeMark)
        {
                googleMapZoom('world');
                setGmapLocationStatus("[unknown location]");
                return;
        }

        var point = new GLatLng(placeMark.Point.coordinates[1], placeMark.Point.coordinates[0]);
        var zoom = convertGmapAccuracyToZoom(placeMark.AddressDetails.Accuracy);
        window.googleMapObject.setCenter(point, zoom);
        setGmapLocationStatus(placeMark.address);
        //var msg = document.getElementById('gmap_search_status').innerHTML + " - " + placeMark.AddressDetails.Accuracy;
        //setGmapLocationStatus(msg);
}

function setGmapLocationStatus(statusMsg)
{
        document.getElementById('gmap_search_status').innerHTML = statusMsg;
}

// http://www.google.com/apis/maps/documentation/reference.html#GGeoAddressAccuracy
function convertGmapAccuracyToZoom(accuracy)
{
        switch (accuracy)
        {
                case 0:
                        return 2;
                        break;
                case 1:
                        return 4;
                        break;
                case 2:
                        return 5;
                        break;
                case 3:
                        return 6;
                        break;
                case 4:
                        return 10;
                        break;
                case 5:
                        return 12;
                        break;
                case 6:
                        return 13;
                        break;
                case 7:
                        return 14;
                        break;
                case 8:
                        return 15;
                        break;
        }
}

