/*
 * ADD MISSING METHODS TO BUILT-IN OBJECTS
 */
if(!Array.prototype.indexOf)
{
    Array.prototype.indexOf = function(elt /*, from*/) {
        var len = this.length;
        var from = Number(arguments[1]) || 0;
        from = (from < 0)
             ? Math.ceil(from)
             : Math.floor(from);
        if(from < 0)
          from += len;
    
        for(; from < len; from++) {
          if (from in this &&
              this[from] === elt)
            return from;
        }
        return -1;
    };
}

if(!Array.prototype.lastIndexOf) {
    Array.prototype.lastIndexOf = function(elt /*, from*/) {
        var len = this.length;
        var from = Number(arguments[1]);
        if(isNaN(from)) {
            from = len - 1;
        } else {
            from = (from < 0)
                ? Math.ceil(from)
                : Math.floor(from);
            if(from < 0)
                from += len;
            else if (from >= len)
                from = len - 1;
        }

        for(; from > -1; from--) {
            if(from in this &&
               this[from] === elt)
                return from;
        }
        return -1;
    };
}

if(!Array.prototype.filter) {
    Array.prototype.filter = function(fun /*, thisp*/) {
        var len = this.length;
        if(typeof fun != "function")
            throw new TypeError();

        var res = new Array();
        var thisp = arguments[1];
        for(var i = 0; i < len; i++) {
            if(i in this) {
                var val = this[i]; // in case fun mutates this
                if(fun.call(thisp, val, i, this))
                    res.push(val);
            }
        }
    
        return res;
    };
}

if(!Array.prototype.forEach) {
    Array.prototype.forEach = function(fun /*, thisp*/) {
        var len = this.length;
        if(typeof fun != "function")
            throw new TypeError();

        var thisp = arguments[1];
        for(var i = 0; i < len; i++) {
            if(i in this)
                fun.call(thisp, this[i], i, this);
        }
    };
}

if(!Array.prototype.every) {
    Array.prototype.every = function(fun /*, thisp*/) {
        var len = this.length;
        if(typeof fun != "function")
            throw new TypeError();

        var thisp = arguments[1];
        for(var i = 0; i < len; i++) {
            if(i in this &&
               !fun.call(thisp, this[i], i, this))
                return false;
        }

        return true;
    };
}

if(!Array.prototype.map) {
    Array.prototype.map = function(fun /*, thisp*/) {
        var len = this.length;
        if(typeof fun != "function")
            throw new TypeError();

        var res = new Array(len);
        var thisp = arguments[1];
        for(var i = 0; i < len; i++) {
            if(i in this)
                res[i] = fun.call(thisp, this[i], i, this);
        }

        return res;
    };
}

if(!Array.prototype.some) {
    Array.prototype.some = function(fun /*, thisp*/) {
        var len = this.length;
        if(typeof fun != "function")
            throw new TypeError();

        var thisp = arguments[1];
        for(var i = 0; i < len; i++) {
            if(i in this &&
              fun.call(thisp, this[i], i, this))
                return true;
        }

        return false;
    };
}

var app = {
	next_sshot: null,
	lang: function(s) {
		return s;
	},
    dlg: function(options) {
        var opts =
        {
            type: 'alert',              // alert|confirm
            title: '',                  // Dialog title
            body: '',                   // Dialog body
            width: 330,
            height: 150,
            context: null,
            draggable: true,
            modal: true,
            resizable: false,
            buttons: {},
            callbacks: {}                // Callbacks - will be called in context scope chain if provided
        };
        $.extend(opts, options);

        var dlg_id = 'dlg-' + Math.round(Math.random()*1000000000);
        var dlg_html = '<div id="' + dlg_id + '" title="' + opts.title + '" class="cms"><p>' + opts.body + '</p></div>';
        var dlg_buts = {};
        var context = opts.context;

        for(var but in opts.buttons) {
            var cb = 'on_'+but;
            if(cb in opts.callbacks) {
                var cb_func = opts.callbacks[cb];
                if(context) {
                    dlg_buts[opts.buttons[but]] = (function(f) {
                        return function() {
                            f.call(context, this);
                        };
                    })(cb_func);
                } else {
                    dlg_buts[opts.buttons[but]] = (function(f) {
                        return function() {
                            f(this);
                        };
                    })(cb_func);
                }
            } else {
                dlg_buts[opts.buttons[but]] = function(){};
            }
        }
        $(dlg_html).dialog(
            {
                draggable: opts.draggable,
                modal: opts.modal,
                resizable: opts.resizable,
                width: opts.width,
                height: opts.height,
                buttons: dlg_buts
            }
        );
    },
    alert: function(title, body) {
        app.dlg(
            {
                title: !body ? app.lang('Alert') : title,
                body: !body ? title : body,
                buttons: {
                    ok: app.lang('OK')
                },
                callbacks: {
                    on_ok: function(dlg) {
                        $(dlg).dialog('close');
                    }
                }
            }
        );
    }, 
    confirm: function(title, body, callback) {
        app.dlg(
            {
                title: !body ? app.lang('Confirm') : title,
                body: !body ? title : body,
                buttons: {
                    yes: app.lang('Yes'),
                    no: app.lang('No')
                },
                callbacks: {
                    on_no: function(dlg) {
                        $(dlg).dialog('close');
                        callback(false);
                    },
                    on_yes: function(dlg) {
                        $(dlg).dialog('close');
                        callback(true);
                    }
                }
            }
        );
    },
    loadDialog: function(url, width, height) {
    	app.lightbox = $.modal($('<div></div>').load(url, {},
    		function() {
    			$('a.dialogCloseImg').click(
    				function(e) {
    					e.preventDefault();
    					app.lightbox.close();
    				}
    			)
    		}), {
            overlayCss: {
    	        backgroundColor: '#000',
    	        cursor: 'wait'
    	    },
            containerCss: {
    	        height: height,
    	        width: width,
    	        backgroundColor: 'transparent',
    	        border: '0px solid #ccc'
            },
            onOpen: function(dialog) {
            	dialog.container.children('.modalCloseImg').hide();
                dialog.overlay.show();
                dialog.container.show();
                dialog.data.show();
            },
            onClose: function(dialog) {
                dialog.data.hide();
                dialog.container.hide();
                dialog.overlay.hide();
                $.modal.close();
            }
    	});
    },
    showDialog: function(html, width, height) {
    	app.lightbox = $(html).modal(
    		{
	            overlayCss: {
	    	        backgroundColor: '#000',
	    	        cursor: 'wait'
	    	    },
	            containerCss: {
	    	        height: height,
	    	        width: width,
	    	        backgroundColor: 'transparent',
	    	        border: '0px solid #ccc'
	            },
	            onOpen: function(dialog) {
	            	dialog.container.children('.modalCloseImg').hide();
	                dialog.overlay.show();
	                dialog.container.show();
	                dialog.data.show();
	                $(window).bind('keypress keydown',
	                	function(e) {
	                		if(e == null) {
	                			var keycode = event.keyCode;
	                		} else {
	                			var keycode = e.which;
	                		}
	                		if(keycode == 27) {
	                			e.preventDefault();
	                			window.app.closeDialog();
	                		}
	                	}
	                )
	            },
	            onClose: function(dialog) {
	                dialog.data.hide();
	                dialog.container.hide();
	                dialog.overlay.hide();
	                $.modal.close();
	            }
    		}
    	);
    },
    closeDialog: function(id) {
    	$(id).unbind();
    	$.modal.close();
    },
    modalWait: function(state) {
    	if(state) {
    		$('<div></div>').modal({
	            overlayCss: {
	    	        backgroundColor: '#000',
	    	        cursor: 'wait'
	    	    },
	            containerCss: {
	    	        height: 100,
	    	        width: 100,
	    	        backgroundColor: 'transparent',
	    	        border: '0px solid #ccc'
	            },
	            onOpen: function(dialog) {
	            	dialog.container.children('.modalCloseImg').hide();
	                dialog.overlay.show();
	                dialog.container.show();
	                dialog.data.show();
	            },
	            onClose: function(dialog) {
	                dialog.data.hide();
	                dialog.container.hide();
	                dialog.overlay.hide();
	                $.modal.close();
	            }
	    	});
    	} else {
    		$.modal.close();
    	}
    },
    doSignup: function() {
		var email = $('#signup-email')[0];
		this.modalWait(true);
		$.post(
			'/index/signup',
			{email:email.value},
            function(data, textStatus) {
				app.modalWait(false);
				if(data.result != undefined && data.result == true) {
					//alert('Thanks!');
					$('#signup-outer').hide();
					$('#signup-buynow').show();
					app.doSignupPost(email.value);
				} else {
					alert('Please check email address!');
				}
			},
		    "json"
		);
    },
    doSignupPost: function(email) {
    	$('#signup-post-email')[0].value = email;
    	$('#signup-post-form')[0].submit();
    },
    cycleSshot: function() {
    	var g_sshots = window.game_sshots;
    	var sshot = $('#game-sshot');
    	var i = g_sshots.indexOf(sshot[0].src);
    	var j = ((i+1) >= g_sshots.length ? 0 : (i+1));
//    	sshot[0].src = g_sshots[j];
    	app.next_sshot = new Image();
    	$(app.next_sshot).load(
    		function() {
    			$('#game-sshot-bg').css('background-image', 'url(' + app.next_sshot.src + ')');
    			sshot.fadeOut(1000,
    				function() {
    					sshot[0].src = app.next_sshot.src;
    					sshot.show();
    					window.setTimeout(app.cycleSshot, 4000);
    			    }
    			);
    		}
    	);
    	app.next_sshot.src = g_sshots[j];
    },
    onLoad: function() {
        $.ajaxSetup(
            {
                beforeSend: function() {
                    if(window.document && window.document.body) window.document.body.style.cursor = "wait";
                },
                complete: function() {
                    if(window.document && window.document.body) window.document.body.style.cursor = "auto";
                }
            }
        );

        $('#tgl-strip-inner img.nav-but').hover(
        	function(e) {
        		this.src = this.src.replace(/1\.gif/, '2.gif');
            },
            function(e) {
            	this.src = this.src.replace(/2\.gif/, '1.gif');
            }
        );

//        $('#nav-bookmark').sSelect();

        $('#nav-bookmark').sSelect().change(
        	function() {
        		var url = $.trim(this.options[this.selectedIndex].value);
        		if(url.length > 0) {
        			location.href = url;
        		}
        	}
        );

        $('a,button').focus(function(e){this.blur();});

        $('#nav-suggest, #foot-suggest').click(
        	function(e) {
        		e.preventDefault();

                $('#suggest-dlg .g_title')[0].value = "";
                $('#suggest-dlg .g_link')[0].value = "";
	            $('#suggest-dlg .dlg-state-open').show();
	            $('#suggest-dlg .dlg-state-done').hide();

        		window.app.showDialog('#suggest-dlg', 512, 312);
        		$('#suggest-dlg .cancel, #suggest-dlg .close').click(
        			function(e) {
        				e.preventDefault();
        				window.app.closeDialog('#suggest-dlg');
        			}
        		);
        		$('#suggest-dlg .ok').click(
        			function(e) {
        				e.preventDefault();
        				if($(this).parent().hasClass('disabled')) {
        				    return;
        				}
        				var title = $.trim($('#suggest-dlg .g_title')[0].value);
        				var link = $.trim($('#suggest-dlg .g_link')[0].value);
//        				alert('title = ' + title + "\nlink = " + link);
//        				window.app.closeDialog('#suggest-dlg');
        				$.getJSON(
        				    '/index/suggest',
        				    {'title':title, 'link':link},
        				    function(data, textStatus) {
        				        if(console)
        				            console.debug(data);
        				        if(data.success == true) {
        				            $('#suggest-dlg .dlg-state-open').hide();
        				            $('#suggest-dlg .dlg-state-done').show();
        				        }
        				    }
        				 );
        			}
        		);
                $('#suggest-dlg .g_title, #suggest-dlg .g_link').bind(
                    "blur focus click mousedown mouseup change keydown keypress keyup",
                    function(e) {
                        var title = $.trim($('#suggest-dlg .g_title')[0].value);
                        var link = $.trim($('#suggest-dlg .g_link')[0].value);
                        if(title.length>0 && link.length>0) {
                            $('#suggest-dlg .ok').parent().removeClass('disabled');
                        } else {
                            $('#suggest-dlg .ok').parent().addClass('disabled');
                        }
                    }
                );
        		$('#suggest-dlg .g_title')[0].focus();
        	}
        );

        if($('#game-info').css('overflow') == 'visible') {
//            var game_info = $('#game-info');
            if($.browser.safari != true) {
                var game_info = $('#game-info').replaceWith(
    	        	$('<iframe style="width: 100%; height: 100%; visibility: hidden;" src=' + "'" + 'javascript:""' + "'" + ' id="game_info_fr" class="game_info" frameborder="0" allowtransparency="true"></iframe>').load(
    	        		function() {
    	        			var contents = $('#game_info_fr').contents();
    	        			var head = contents.find('head');
    	        			var body = contents.find('body');
    	        			contents.find('html').addClass('game_info');
    	        			body.addClass('game_info');
    	        			game_info.addClass('over-vis');
    	        			$(document).find('link[rel=stylesheet]').clone().appendTo(head);
    	        			body.append(game_info);
    	        			$('#game-info', body).css('visibility', 'visible');
    	        			$('#game_info_fr').css('visibility', 'visible');
    	        	    }
    	        	)
    	        );
            } else {
                $('#game-info').css('visibility', 'visible');
            }

	        if(window.game_sshots) {
	        	window.setTimeout(app.cycleSshot, 2000);
	        }
        } else {
        	$('#game-info').css('visibility', 'visible');
        }

        if(window.app_page && window.app_page.onLoad) {
        	window.app_page.onLoad();
        }
    } 
}

$(document).ready(
    function() {
        window.app.onLoad();
    }
);
