/*
 * 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 = {
    page: null,
    dlg: function(options) {
        var opts =
        {
            type: 'alert',              // alert|confirm
            title: '',                  // Dialog title
            body: '',                   // Dialog body
            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: 330,
                height: 150,
                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);
                    }
                }
            }
        );
    },
    showBigPhoto: function() {
        $('<div><img class="photo-big" src="' + app.big_photo.src + '" border="0"/></div>').modal({
            overlayCss: {
                backgroundColor: '#000',
                cursor: 'wait'
            },
            containerCss: {
                height: app.big_photo.height,
                width: app.big_photo.width,
                backgroundColor: '#fff',
                border: '12px solid #fff'
            },
            onOpen: function(dialog) {
                dialog.overlay.fadeIn('fast', function() {
                    dialog.container.show('fast', function() {
                        dialog.data.fadeIn('fast', function() {
                        	var big_links = $('#photo-big-links');
                        	dialog.data.prepend(big_links);
//                        	big_links.show();
                        });
                    });
                });
            },
            onClose: function(dialog) {
            	var big_links = $('#photo-big-links');
            	big_links.hide();
            	$('#photo-panel-player').prepend(big_links);

                dialog.data.fadeOut('fast', function() {
                    dialog.container.hide('fast', function() {
                        dialog.overlay.fadeOut('fast', function() {
                            $.modal.close();
                        });
                    });
                });
            }
        });
    },
    showPhoto: function(url) {
        app.big_photo = new Image();
        app.big_photo.onload = function(){app.showBigPhoto();};
        app.big_photo.src = url;
    },
    showBigPhoto2: function(url) {
        app.lightbox = $('<div><img class="photo-img photo-load" src="/assets/trans.gif" border="0"/></div>').modal({
            overlayCss: {
                backgroundColor: '#000',
                cursor: 'wait'
            },
            containerCss: {
                height: 300,
                width: 300,
                backgroundColor: '#fff',
                border: '12px solid #fff'
            },
            onOpen: function(dialog) {
            	dialog.container.children('.modalCloseImg').hide();
                dialog.overlay.fadeIn('fast', function() {
                    dialog.container.show("scale", {}, 700, function() {
                        dialog.data.show();

                        app.big_photo = new Image();
                        app.big_photo.onload = function() {
                        	var photo_img = dialog.data.children('.photo-img').eq(0);
                        	photo_img.removeClass('photo-load');
                        	
                            dialog.container.effect("size", { to: {width: app.big_photo.width, height: app.big_photo.height}, origin: ['middle','center'] }, 700, function() {
                            	$(window).trigger('resize.simplemodal');
                            	photo_img.attr('src', app.big_photo.src);
                            	photo_img.width(app.big_photo.width);
                            	photo_img.height(app.big_photo.height);
                            	dialog.container.children('.modalCloseImg').show();
                            });
                        };
                        app.big_photo.src = url;
                    });
                });
            },
            onClose: function(dialog) {
                dialog.data.fadeOut('fast', function() {
                    dialog.container.hide('fast', function() {
                        dialog.overlay.fadeOut('fast', function() {
                            $.modal.close();
                        });
                    });
                });
            }
        });
    },
    showSWF: function(swf_url, swf_width, swf_height) {
        app.lightbox = $('<div id="swfwin"><img class="photo-img photo-load" src="/assets/trans.gif" border="0"/></div>').modal({
            overlayCss: {
                backgroundColor: '#000',
                cursor: 'wait'
            },
            containerCss: {
                height: swf_height,
                width: swf_width,
                backgroundColor: '#fff',
                border: '12px solid #fff'
            },
            onOpen: function(dialog) {
            	dialog.container.children('.modalCloseImg').hide();
                dialog.overlay.fadeIn('fast', function() {
                    dialog.container.show("scale", {}, 700, function() {
                        dialog.data.show();

                        var so = new SWFObject(swf_url, "swfwin_obj", swf_width, swf_height, "8", "#000000");
                        so.addParam("MENU", "FALSE");
                        so.addParam("wmode", "transparent");
                        so.addParam("allowScriptAccess", "never");
                        so.addParam("allowfullscreen", "false");
                        so.write("swfwin");

                    	dialog.container.children('.modalCloseImg').show();
                    });
                });
            },
            onClose: function(dialog) {
                dialog.data.fadeOut('fast', function() {
                    dialog.container.hide('fast', function() {
                        dialog.overlay.fadeOut('fast', function() {
                            $.modal.close();
                        });
                    });
                });
            }
        });
    },
    showPhoto2: function(url) {
    	app.showBigPhoto2(url);
    },
    showGame: function() {
    	app.showSWF("http://assets.magicballerina.com/content/apache_game.swf", 667, 497);
    },
    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";
                }
            }
        );

//        $('body').html($('body').html().replace(/Apache/g, '<i>Apache</i>'));

        $('a#register').click(
        	function(e) {
        		e.preventDefault();
        		$('#reg-done-cont').hide();
        		$('#reg-form-cont').show();
                $('#reg-outer').show();
            }
        );

        $('a#reg-form-submit').click(
        	function(e) {
        		e.preventDefault();
        		var email = $('#reg-email')[0];
        		$.post(
        			'/index/register',
        			{email:email.value},
                    function(data, textStatus) {
                    	$('#reg-form-cont').hide();
                    	$('#reg-done-cont').show();
        			},
        		    "json"
        		);
        	}
        );

        $('a#reg-form-close').click(
        	function(e) {
        		e.preventDefault();
                $('#reg-outer').hide();
        	}
        );

        $('a.photo-link').click(
            function(e) {
                e.preventDefault();
                $('#photo-show').attr('href', $(this).attr('href'));
                $('#photo-small').attr('src', this.id);

                $('img.photo-big').attr('src', $(this).attr('href'));

                var img = $('img', this).get(0);
                var num = $(img).attr('class');

                $('a.photo-link img').each(
                	function(i) {
                		if($(this).hasClass(num)) {
                			this.src = this.src.replace(/a\.gif/, 'b.gif');
                		} else {
                			this.src = this.src.replace(/b\.gif/, 'a.gif');
                		}
                	}
                );
            }
        );

        $('a#photo-show').click(
            function(e) {
                e.preventDefault();
                app.showPhoto2($(this).attr('href'));
            }
        );

        $('a#game-show').click(
        	function(e) {
        		e.preventDefault();
                app.showGame();
        	}
        );

        $('#tabs img.off').hover(
        	function(e) {
        		$(this).addClass('on');
            },
            function(e) {
            	$(this).removeClass('on');
            }
        );

        $('a,button').focus(function(e){this.blur();});

        if(app.page && app.page.onLoad) {
            app.page.onLoad();
        }
    } 
}

$(document).ready(
    function() {
        app.onLoad();
    }
);