/**
 *                O$$$7$
 *          $7$$$$$$$$$
 *        $$$$$
 *       $$$
 *       $$8                                                7$$$$$8
 *       $$$        D$7$$$$$                                7    7$$$$N
 *       7$$        $    Z$$ Z                                       $$7
 *        $$              $ D$8                           O$$$$$7D   $$D
 *        $$$            $$ 7$$                 $  $   O7$ $$N  77$$$$$
 *        $$$        Z$$$$  $$  N       7$$  $ $    $$$N  7 7       $$$
 *         7$$$$$$$$$$$    7$$$$$$$$$$O7   8$$$$   7 O     $DO       $O
 *                         7$7      7$$ 77$   $      $N  7  7 D$$D  7$
 *                         $7         $$$8  8Z        8N   $
 *                        $$          $$$               7$
 *                        $$         8$$
 *                         7$$       $$7
 *                               O$$$$
 * 
 * Play Anywhere, Anytime. Gbanga is the mixed-reality mobile game where
 * you must take-over as many real-world bars to become the supreme Mafioso!
 *
 * Copyright (c) 2007-2011 Gbanga, Millform AG. All rights reserved.
 *
 * @author Matthias
 * @version 2011
 * @platform Desktop IE/Opera/Firefox/Safari
 *
 * Disclaimer and licenses:
 * 
 * - ASCII art above was generated with glassgiant.com
 * - The Gbanga website uses OpenLayers, the Free Maps for the Web JavaScript Library, http://openlayers.org, http://svn.openlayers.org/trunk/openlayers/license.txt
 * - The Gbanga website uses jQuery: The Write Less, Do More, JavaScript Library, http://jquery.com, http://github.com/jquery/jquery/blob/master/MIT-LICENSE.txt
 * 
 */

j = jQuery.noConflict();

if (typeof(G) === 'undefined') {
    G = {};
};

G.Marquee = {
    init: function() {
        var arr = j("#features > div");
        arr.hide();
        j(arr[Math.floor(Math.random() * arr.length)]).show();
        
        this.addMarqueeJumpingLinksToTitles();
        this.startMarquee();
    },
    addMarqueeJumpingLinksToTitles: function() {
        var titles = j("#features > div > h1:not(:has(span[class=marqueeIndex]))");
        titles.each(function(i, e) {
            j(e).append(' <span class="marqueeIndex"><a class="showprevious" title="< Back" href="#">&lt;</a> <a class="shownext" title="Next >" href="#">&gt;</a></span>');
        });
        
        j(".showprevious").click(this.previous);
        j(".shownext").click(this.next);
    },
    INTERVAL:4500,
    previous: function(event) {
        G.Marquee.stopMarquee();
        if (event && event.preventDefault) {
            try {
                event.preventDefault();
            } catch (e) {}
        }
        var selected = j("#features > div:visible");
        
        if (selected && selected.length && selected.length > 0) {
            G.Marquee._next = j(selected[selected.length - 1]).next();
            if (G.Marquee._next.length == 0) {
                G.Marquee._next = j("#features > div").first();
            }
            selected.css('position', 'relative');
            selected.animate({
                left: '+=300'}, 300, function() {
                    selected.hide();
                    var p = j(G.Marquee._next);
                    p.css('position', 'relative');
                    p.css('left', '-300px');
                    p.show();
                    p.animate({
                        left: '+=300'}, 300);                
                });            
        }
        G.Marquee.startMarquee();
    },
    next: function(event) {
        G.Marquee.stopMarquee();
        if (event && event.preventDefault) {
            try {
                event.preventDefault();
            } catch (e) {}
        }
        var selected = j("#features > div:visible");
        
        if (selected && selected.length && selected.length > 0) {
            // G.Marquee._previous = selected[0].previousElementSibling;
            G.Marquee._previous = j(selected[0]).prev();
            if (G.Marquee._previous.length == 0) {
                // G.Marquee._previous = selected[0].parentNode.lastElementChild;
                G.Marquee._previous = j("#features > div").last(); // selected[selected.length - 1];
            }
            // selected.slideUp(300, function() { j(G.Marquee._previous).slideDown(300); });
            selected.css('position', 'relative');
            selected.animate({
                left: '-=300'}, 300, function() {
                    selected.hide();
                    var p = j(G.Marquee._previous);
                    p.css('position', 'relative');
                    p.css('left', '300px');
                    p.show();
                    p.animate({
                        left: '-=300'}, 300);
                });
        }         
        G.Marquee.startMarquee();
    },
    startMarquee: function() {
        if (j("#features > div").length > 0) {
            clearTimeout(this.marqueeTimer);
            this.marqueeTimer = setTimeout("G.Marquee.next();", this.INTERVAL);
        }
    },
    stopMarquee: function() {
        clearTimeout(this.marqueeTimer);
    }
};

G.Find = {
    find: function(query) {
        var host =  window.location.host;
        host = host.replace('status.', '');
        var url = window.location.protocol + "//" + host + "/find/";
        window.location = url + query;
    },
    init: function() {
        j("#find").keypress(function(event) {
            if (event.keyCode === 13) {
                G.Find.find(j("#find")[0].value);
            }
        });
        j("#find").click(function(event) {
            console.info("width=" + j("#find").width() + ",offset-left=" + j("#find").offset().left + ",event.clientX=" + event.clientX);
            if (j("#find").width() + j("#find").offset().left - event.clientX < 15) {
                G.Find.find(j("#find")[0].value);
            }
        });
        j("#find").focus(function() {
            var f = j("#find")[0];
            if (f && f.value === j(f).attr('_cleaned')) {
                f.value = "";
            }
        });
        j("#find").blur(function() {
            var f = j("#find")[0];
            if (f && f.value.length === 0 && j(f).attr('_cleaned') !== 'undefined') {
                f.value = j(f).attr('_cleaned');
            }
        });
    }
};

G.CollapsableTitles = {
    init: function() {
        j(".content li :not(h2:first-child,.alwaysshown)").hide();
        var headers = j(".content li h2:first-child");
        headers.css('text-decoration', 'underline');
        headers.css('cursor', 'pointer');
        headers.unbind('click').click(function(event) {
            if (event.currentTarget && event.currentTarget.parentNode) {
                var items = j(":not(h2:first-child,.alwaysshown)", event.currentTarget.parentNode);
                if (items.is(":visible")) {
                    j(event.currentTarget).css('text-decoration', 'underline');
                    j(event.currentTarget).css('cursor', 'pointer');
                    items.hide();
                } else {
                    items.show();
                    j(event.currentTarget).css('text-decoration', 'none');
                    j(event.currentTarget).css('cursor', 'default');
                }
            }
        });
    }
};

G.CreateIndex = {
    init: function(headlineFilter) {
        var index = j(document.createElement("div"));
        j(headlineFilter).each(function(i,e) {
            e = j(e);
            var caption = e.text();
            var name = escape(caption);
            index.append('<a href="#' + name + '">' + caption + '</a>');
            e.prepend('<a name="' + name + '"/>');
            e.click(function(event) {
                // window.location.hash = "__first";
                scrollTo(0,0);
            });
        });
        index.addClass("index");
        j(j(headlineFilter)[0]).before(index);
        // index.before('<a name="__first"/>');
    }
    
    
};

j(document).ready(function() {
    G.Find.init();
    G.Marquee.init();
});


G.Scroll = {
    
    INTERVAL: 5000,
    _width: 320,
    init: function(img, count, width) {
        this._count = count;
        this._img = j(img);
        if (width) {
            this._width = width;
        }
        this._i = 0;
        this._interval = setInterval(this.next, this.INTERVAL);
    },
    next: function() {
        G.Scroll._i++;
        if (G.Scroll._i == G.Scroll._count) {
            G.Scroll._img.animate({left: '0'}, 300);
            G.Scroll._i = 0;
        } else {
            G.Scroll._img.css('position', 'relative');
            G.Scroll._img.animate({left: '-=' + G.Scroll._width}, 300);
        }
        
    }
};

/**
  * Handy cookie tool.
  * 
  * Taken from http://www.quirksmode.org/js/cookies.html#script
  */
G.Cookie = {
	/**
	 * When calling createCookie() you have to give it three bits of information:
	 * 
	 *  - the name and
	 *  - value of the cookie and
	 *  - the number of hours it is to remain active.
	 *
	 */
	set: function(name, value, hours) {
		var expires;
		if (hours) {
			var date = new Date();
			date.setTime(date.getTime() + (hours * 3600000));
			expires = "; expires=" + date.toGMTString();
		} else {
			expires = "";
		}
		document.cookie = name + "=" + value + expires + "; path=/";
	},
	
	/**
	 * To read out a cookie, call this function and pass the name of the cookie.
	 */
	get: function(name, defaultValue) {
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for(var i=0; i < ca.length; i++) {
			var c = ca[i];
			while (c.charAt(0) == ' ') {
				c = c.substring(1, c.length);
			}
			if (c.indexOf(nameEQ) === 0) {
				return c.substring(nameEQ.length, c.length);
			}
		}
		if (typeof(defaultValue) == 'undefined') {
			return undefined;
		} else {
			return defaultValue;
		}
	},
	
	/**
	 * Pass the name of the cookie to be erased
	 */
	erase: function(name) {
		this.set(name,"",-1);
	}
};

G.animate_map = function() {
    var o = null;
    var i = 0;
    while (o == null && i++ < 10) {
        switch (parseInt(Math.random() * 3)) {
            case 0:
                if (recentActivity._newbies.length > 0) {
                    o = recentActivity._newbies[parseInt(Math.random() * recentActivity._newbies.length)];
                    j("#bubbleTitle").html("Just signed up");
                    j("#bubbleIcon").attr("src", o.avatar);
                    j("#bubbleIcon").attr("height", 54);
                    j("#bubbleIcon").attr("width", 54);
                    j("#bubbleText").html("<a href=\"/who/" + o.username + "\">" + o.username + "</a>" + (o.near !== undefined ? "<br><small>Near " + o.near + "</small>" : ""));
                    break;
                }
            case 1:
                if (recentActivity._shouts.length > 0) {
                    o = recentActivity._shouts[parseInt(Math.random() * recentActivity._shouts.length)];
                    j("#bubbleTitle").html("<a href=\"/who/" + o.username + "\">" + o.username + "</a> just shouted at <a href=\"/where/" + o.cell + "\">" + o.cell + "</a>:");
                    j("#bubbleIcon").attr("src", o.avatar);
                    j("#bubbleIcon").attr("height", 54);
                    j("#bubbleIcon").attr("width", 54);
                    j("#bubbleText").html("<em>&quot;" + o.message + "&quot;</em>" + (o.near !== undefined ? "<br><small>Near " + o.near + "</small>": ""));
                    break;
                }
            case 2:
            default:
                if (recentActivity._discoveries.length > 0) {
                    o = recentActivity._discoveries[parseInt(Math.random() * recentActivity._discoveries.length)];
                    j("#bubbleTitle").html("<a href=\"/who/" + o.username + "\">" + o.username + "</a> just discovered:");
                    j("#bubbleIcon").attr("src", o.flag);
                    j("#bubbleIcon").attr("height", 35);
                    j("#bubbleIcon").attr("width", 49);
                    j("#bubbleText").html("<a href=\"/where/" + o.cell + "\">" + o.cell + "</a>" + (o.near !== undefined ? "<br><small>Near " + o.near + "</small>": ""));
                    break;
                }
        }
    }
    if (o !== null) {
        var _lon = o.lon;
        var _lat = o.lat;
        map.panTo(new OpenLayers.LonLat(_lon, _lat).clone().transform(map.displayProjection, map.getProjectionObject()));
        j("#bubble").show();
        j("#bubbletip_tr").show();
    } else {
        j("#bubble").hide();
        j("#bubbletip_tr").hide();
    }
};

G.login = function(nickname, password) {
    j("#quickloginbutton").hide();
    j("#quickloginwait").show();
    j.ajax({
        type: 'POST',
        url : "/_login",
        data: {
            'nickname' : nickname,
            'password' : password },
        success: function(data, textStatus, xhr) {
            if (data == 'true') {
                window.location = "/profile";
            } else {
                j("#quickerror").show();
                j("#quicklogin").addClass("wrong");
                j("#quickloginbutton").show();
                j("#quickloginwait").hide();
            }
        },
        error: function(xhr, textStatus, errorThrown) {
            j("#quickloginbutton").show();
            j("#quickerror").text(textStatus);
            j("#quickerror").show();
            j("#quicklogin").addClass("wrong");
            j("#quickloginbutton").show();
            j("#quickloginwait").hide();
        }
    });
};

G.logout = function(url) {
    var _logout = function() {
        if (FB && FB.Connect && FB.Connect.logout) {
            try {
                FB.Connect.logout();
            } catch (e) {}
        }
        window.location = url;
    }
    if (typeof(FB) === 'undefined') {
        j.getScript("http://connect.facebook.net/en_US/all.js#appId=51583559166&xfbml=1&cookie=1&status=1", function(data, textStatus) {
          FB.init({ 
             appId:'51583559166',
             cookie:true, 
             status:true,
             xfbml:true
          });
          _logout();
       });        
    } else {
        _logout();
    }
};

G.animate_gbangoo = function(element, times, fps) {
    
    var i = 0;
    var timerId = setInterval(function() {
        element.style.backgroundRepeat = "no-repeat";
        element.style.backgroundPosition = "-" + (i * 54) + "px 0px";
        i = (i + 1) % times;
    }, 1000 / fps);
    
    return timerId;
    
};

G.stop_gbangoo_animation = function(timerId) {
    clearInterval(timerId);
};

// based on vtip: http://www.vertigo-project.com/projects/vtip
G.setUpPopups = function() {    
    this.xOffset = -10; // x distance from mouse
    this.yOffset = 10; // y distance from mouse       
    
    j(".popup").unbind().hover(    
        function(e) {
            this.t = this.title;
            this.title = ''; 
            this.top = (e.pageY + yOffset); this.left = (e.pageX + xOffset);
            
            j('body').append( '<div id="popup"><img id="popupArrow" />' + this.t + '</div>' );
            
            j('div#popup #popupArrow').attr("src", '/img/popup_arrow.png');
            j('div#popup').css("top", this.top+"px").css("left", this.left+"px").fadeIn("slow");
        },
        function() {
            this.title = this.t;
            j("div#popup").fadeOut("slow").remove();
        }
    ).mousemove(
        function(e) {
            this.top = (e.pageY + yOffset);
            this.left = (e.pageX + xOffset);
            
            j("div#popup").css("top", this.top+"px").css("left", this.left+"px");
        }
    );            
    
};

G.showPopup = function(content, top, left) {

    G.hidePopup();
    
    j('body').append( '<div id="popup"><img id="popupArrow" />' + content + '</div>' );
                
    j('div#popup #popupArrow').attr("src", '/img/popup_arrow.png');
    
    var yOffset = 50;
    var xOffset = 20;
    
    j('div#popup').css("top", (top+yOffset)+"px").css("left", (left+xOffset)+"px").fadeIn("slow");
    
    j('div#popup').click(function() { j(this).remove(); });
    
};

G.hidePopup = function() {
    j("div#popup").fadeOut("slow").remove();
};

G.hasFacebookSession = function() {
    return document.cookie.indexOf("; fbs_51583559166") > -1;
}

G.pendingMapTiles = 0;

G.getMapTile = function(bounds) {
    // j("#quickloginbutton").hide();
    // j("#quickloginwait").show();
    var t = new Date().getTime();
    
    setTimeout(function() {
    
        if (G.pendingMapTiles > t) {
            return;
        }
        G.pendingMapTiles = t;
        
        // G.pendingMapTiles.push(t);
        // while (G.pendingMapTiles && G.pendingMapTiles[0] !== t) {
            // wait
            // if (G.pendingMapTiles.length == 0) {
                // return;
            // }
        // }
        j.ajax({
            type: 'POST',
            url : "/api",
            data: {
                'm' : 'getMapTile',
                'p0' : bounds.top,
                'p1' : bounds.left,
                'p2' : bounds.bottom,
                'p3' : bounds.right },
            success: function(data, textStatus, xhr) {
                //if (data == 'true') {
                //    window.location = "/profile";
                //} else {
                //    j("#quickerror").show();
                //    j("#quicklogin").addClass("wrong");
                //    j("#quickloginbutton").show();
                //    j("#quickloginwait").hide();
                //}
                var features = data.features;
                _markers.clearMarkers();
                if (G.pendingMapTiles !== t) {
                    return;
                }
                j(features).each(function(i,e) {
                    var name = e.id.substring(5);
                    addMarker(
                        new OpenLayers.LonLat(e.geometry.coordinates[0], e.geometry.coordinates[1]),
                        new OpenLayers.Icon("http://img.gbanga.com/" + e.properties.img, new OpenLayers.Size(49,35), new OpenLayers.Pixel(-25,-18), undefined),
                        name,
                        "/where/" + name
                    );
                });
                // G.pendingMapTiles.shift();
            },
            error: function(xhr, textStatus, errorThrown) {
                //j("#quickloginbutton").show();
                //j("#quickerror").text(textStatus);
                //j("#quickerror").show();
                //j("#quicklogin").addClass("wrong");
                //j("#quickloginbutton").show();
                //j("#quickloginwait").hide();
                // G.pendingMapTiles.shift();
            }
        });
    }, 100);
};
