/**
 * Oculi.com Main JavaScript
 * Copyright @2007-2008 Oculi LLC.  All rights reserved.
 *
 * This file builds dynamic portions of the interface such as
 * AJAX-loaded broadcast manifests and controls playlist elements
 * and their interactivity (browsing, scanning, etc.). It also 
 * contains JS-to-AS communications, cookie persistence functions
 * and custom Google Maps functionality.
 */
 
// Flash Player Functionality

/**
 * Gets the specified flash movie object for communication
 * @return an embed or object element
 */
function getFlashMovieObject(movie) {
    if (window.document[movie]) {
        return window.document[movie];
    } else if (isIE) {
        return document.getElementById(movieName);
    } else if (document.embeds && document.embeds[movieName]) {
        return document.embeds[movieName];
    }
}

/**
 * Sets the uri / id of the stream to be loaded by the
 * stream player flash component.
 */
function setStreamPlayerUri(uri) {
    var flashMovie = getFlashMovieObject("stream_player");
    flashMovie.SetVariable("/:streamUri", uri);
}



/**
 * Loads a div with a flash panel that sets shared object "cookies"
 * for the functional flash-based elements of the website.
 */
function displaySettingsPanel() {

}


// Broadcast Index Functionality

var broadcastPage = new Array();
broadcastPage["current"] = 1;
broadcastPage["archive"] = 1;

function initManifest() {
    populateBroadcasts("archive");
	populateArticles("archive");
}

/**
 * Load broadcasts.
 */
function populateBroadcasts(type) {
    var d = new Date();
    $("#" + type + "Broadcasts").load("/remote/broadcasts?type=" + type + "&page=" + broadcastPage[type] + "&time=" + d.getTime(), onBroadcastsLoaded());
}
function populateArticles(type) {
    var d = new Date();
    $("#" + type + "Articles").load("/remote/articles.php?type=" + type + "&page=" + broadcastPage[type] + "&time=" + d.getTime(), onArticlesLoaded());
}
function loadBroadcastPage(type, pageDelta) {
    //$("#" + type).
    broadcastPage[type] += pageDelta;
    if (broadcastPage[type] < 1) broadcastPage[type] = 1;
    populateBroadcasts(type);
}
function loadArticlePage(type, pageDelta) {
    //$("#" + type).
    broadcastPage[type] += pageDelta;
    if (broadcastPage[type] < 1) broadcastPage[type] = 1;
    populateArticles(type);
}
/**
 * Broadcast load event.
 */
function onBroadcastsLoaded() {
    //window.alert("loaded!!!");
}
function onArticlesLoaded() {
    //window.alert("loaded!!!");
}
/**
 * Toggle broadcast panels (view / settings)
 */
function toggleBroadcastPanels(type) {
    $("div."+type+"-panel").toggle();
}

/**
 * Save broadcast pane settings
 */
function saveBroadcastSettings(type) {
    /*
    DEPRECATED
    var settingsForm = document.getElementById(type + "Settings");
    var inputs = settingsForm.getElementsByTagName("input");
    for(var i = 0; i < inputs.length; i++){
        var input = inputs[i];
        if (input.checked) {
            cookieValue += (i > 0 ? delimiter : "") + input.value;
        }
    }
    */
    
    // jQuery alternative checkbox reading
    var delimiter = "QQQ";
    var cookieValue = "";
    var cookieName = type + "_settings";
    $("#" + type + "Settings input").each(
        function(i) {
            if ($(this).attr("checked")) {
                cookieValue += (cookieValue.length > 0 ? delimiter : "") + $(this).attr("value");
            }
        }
    );
    //window.alert(cookieValue);
    setCookie(cookieName, cookieValue, false);
    populateBroadcasts(type);
    toggleBroadcastPanels(type);
}



// Google Maps Functionality


/**
 * Initializes the MapCast map
 */
function initMap(latitude, longitude) {
    if (GBrowserIsCompatible()) {
        var map = new GMap2(document.getElementById("map"), {size: new GSize(397,296)} );
        map.setCenter(new GLatLng(37.4419, -122.1419), 13);
        map.addControl(new GMapTypeControl());
        map.addControl(new GSmallZoomControl());
        if (latitude != null && longitude != null) {
            setMapCenter(latitude, longitude);
        }
    }
}

/**
 * Sets the center of the MapCast map
 */
function setMapCenter(latitude, longitude) {
    if (GBrowserIsCompatible()) {
        var map = new GMap2(document.getElementById("map"));
        map.setCenter(new GLatLng(latitude, longitude), 13);

        // Custom
        var oculicon = new GIcon();
        /*
        oculicon.image = "images/maps/oculicon_lg.png";
        oculicon.shadow = "images/maps/oculicon_lg_shadow.png";
        oculicon.iconSize = new GSize(16, 40);
        oculicon.shadowSize = new GSize(40, 40);
        oculicon.iconAnchor = new GPoint(8, 40);
        oculicon.infoWindowAnchor = new GPoint(5, 1);
        */

        // Display current streams
        //var mk1 = new GMarker(new GLatLng(latitude, longitude), {icon: oculicon, title: "Stream location", clickable: true, draggable: false});
        //GEvent.addListener(mk1, "mouseup", function() { window.alert("You clicked the stream location"); });
        var mk1 = new GMarker(new GLatLng(latitude, longitude));
        map.addOverlay(mk1);
    }
}

function addMapMarker(latitude, longitude) {
}

function loadMapMarkerStream(marker) {
}

function showStreamMarkers() {
}



// Cookie Functionality

/**
 * Sets a cookie.
 */
function setCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

/**
 * Gets a cookie.
 */
function getCookie(name) {
    var tag = name + "=";
    var cookies = document.cookie.split(';');
    for(var i=0; i < cookies.length; i++) {
        var c = cookies[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(tag) == 0) return c.substring(tag.length, c.length);
    }
    return null;
}

/**
 * Removes a cookie.
 */
function removeCookie(name) {
    setCookie(name, "", -1);
}


// Array Functionality for IE5


/**
 * Array.push() functionality extension for IE5
 */
function arrayPush() {
    var ap = 0;
    for (ap = 0; ap < arguments.length; ap++) {
        this[this.length] = arguments[ap];
    }
    return this.length;
}
if (typeof Array.prototype.push == "undefined") {
    Array.prototype.push = arrayPush;
}

/**
 * Array.shift() functionality extension for IE5
 */
function arrayShift() {
    var as = 0;
    var response = this[0];
    for (as = 0; as < this.length-1; as++) {
        this[as] = this[as + 1];
    }
    this.length--;
    return response;
}
if (typeof Array.prototype.shift == "undefined") {
    Array.prototype.shift = arrayShift;
}

Array.prototype.exists = function (x) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == x) return true;
    }
    return false;
}

/**
 * Find the absolute position of an object
 */
getAbsolutePosition = function(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		} while (obj = obj.offsetParent);
		return [curleft,curtop];
	}
}

/**
 * Cross-browser addEventListener
 */
function addEventSimple(obj,evt,fn) {
	if (obj.addEventListener)
		obj.addEventListener(evt,fn,false);
	else if (obj.attachEvent)
		obj.attachEvent('on'+evt,fn);
}
function removeEventSimple(obj,evt,fn) {
	if (obj.removeEventListener)
		obj.removeEventListener(evt,fn,false);
	else if (obj.detachEvent)
		obj.detachEvent('on'+evt,fn);
}

/**
 * Get an element's style property
 */
function getStyle(el,styleProp)
{
	var x = document.getElementById(el);
	if (x.currentStyle)
		var y = x.currentStyle[styleProp];
	else if (window.getComputedStyle)
		var y = document.defaultView.getComputedStyle(x,null).getPropertyValue(styleProp);
	return y;
}

/**
 * is obj1 inside obj2?
 */
function containsElement(obj1,obj2) {
	if(obj2==null)
		return false;
	while (obj2.nodeName != 'HTML') {
		if (obj2 == obj1) return true;
		obj2 = obj2.parentNode;
	}
	return false;
}	

/**
	get ie version
*/
function getMsieVersion()
{
	var ua = window.navigator.userAgent
	var msie = ua.indexOf ( "MSIE " )

	if ( msie > 0 )      // If Internet Explorer, return version number
	  return parseInt (ua.substring (msie+5, ua.indexOf (".", msie )))
	else                 // If another browser, return 0
   return 0
}