/*
 * 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) {
    	var buts = '' +
		    '<div class="photo-lft-big photo-buts-lft">' +
		    '    <img style="cursor: pointer;" id="photo-lft-big-but" src="/assets/trans.gif" width="53" height="134" border="0"/>' +
		    '</div>' +
		    '<div class="photo-rgt-big photo-buts-rgt">' +
		    '    <img style="cursor: pointer;" id="photo-rgt-big-but" src="/assets/trans.gif" width="53" height="134" border="0"/>' +
		    '</div>';

        app.lightbox = $('<div class="lb-photo-cont" style="position:relative;"><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: '0px 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.css('width', photo_img.outerWidth());
                            		dialog.container.css('height', photo_img.outerHeight());
                            		dialog.container.children('.modalCloseImg').show();
                            		$(window).trigger('resize.simplemodal');
                            		$('.lb-photo-cont').append(buts);
                            		if(app.photoChkPrev()) {
                            			$('.photo-buts-lft').show();
                            		} else {
                            			$('.photo-buts-lft').hide();
                            		}
                            		if(app.photoChkNext()) {
                            			$('.photo-buts-rgt').show();
                            		} else {
                            			$('.photo-buts-rgt').hide();
                            		}
                                    $('#photo-lft-big-but').click(
                                    	function(e) {
                                    		app.photoPrev();
                                    	}
                                    );
                                    $('#photo-rgt-big-but').click(
                                    	function(e) {
                                    		app.photoNext();
                                    	}
                                    );
                            	}
                            );
                        };
                        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($('#game-show').attr('href'), 667, 497);
    },
    photoChkPrev: function() {
		var cur = $('a.photo-link[id="' + $('#photo-small').attr('src') + '"]')[0];
		if(cur) {
			var pos = $.inArray(cur, $('a.photo-link'));
			return (pos > 0);
		}
		return false;
    },
    photoChkNext: function() {
		var cur = $('a.photo-link[id="' + $('#photo-small').attr('src') + '"]')[0];
		if(cur) {
			var len = $('a.photo-link').length;
			var pos = $.inArray(cur, $('a.photo-link'));
			return (pos < (len-1));
		}
		return false;
    },
    photoPos: function() {
    	var pos = -1;
		var cur = $('a.photo-link[id="' + $('#photo-small').attr('src') + '"]')[0];
		if(cur) {
			pos = $.inArray(cur, $('a.photo-link'));
		}
		return pos;
    },
    photoPrev: function() {
		var cur = $('a.photo-link[id="' + $('#photo-small').attr('src') + '"]')[0];
		if(cur) {
			var pos = $.inArray(cur, $('a.photo-link'));
			if(pos > 0) {
				var prev = $('a.photo-link')[pos-1];
                $('#photo-show').attr('href', prev.href);
                $('#photo-small').attr('src', prev.id);

                $('img.photo-big, img.photo-img').attr('src', prev.href);

                if(pos < 2) {
                	$('.photo-buts-lft').hide();
                }
                $('.photo-buts-rgt').show();

                $('.p_credit').hide();
                $('#p_c_' + (pos-1)).show();
			}
		}
    },
    photoNext: function() {
		var cur = $('a.photo-link[id="' + $('#photo-small').attr('src') + '"]')[0];
		if(cur) {
			var len = $('a.photo-link').length;
			var pos = parseInt($.inArray(cur, $('a.photo-link')));
			if(pos < (len-1)) {
				var next = $('a.photo-link')[pos+1];
                $('#photo-show').attr('href', next.href);
                $('#photo-small').attr('src', next.id);

                $('img.photo-big, img.photo-img').attr('src', next.href);

                if(pos == (len-2)) {
                	$('.photo-buts-rgt').hide();
                }
                $('.photo-buts-lft').show();

                $('.p_credit').hide();
                $('#p_c_' + (pos+1)).show();
			}
		}
    },
    goToPage: function(p_num) {
    	if(!p_num) {
    		p_num = $('#nav-p_num')[0].value;
    	}
    	p_num = p_num.replace(/[^0-9]/g, '');
    	if(p_num && !isNaN(p_num)) {
    		location.href = '/' + $('#nav-site_id')[0].value + '/pages/page/' + $('#nav-p_num')[0].value;
    	}
    },
    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();
        	}
        );

        $('form#nav-page_num').submit(
        	function(e) {
        		e.preventDefault();
        		app.goToPage();
        	}
        );

        $('img.submit-but').click(
        	function(e) {
        		e.preventDefault();
        		app.goToPage();
        	}
        );

        $('#photo-lft-sml-but').click(
        	function(e) {
        		app.photoPrev();
        	}
        );

        $('#photo-rgt-sml-but').click(
        	function(e) {
        		app.photoNext();
        	}
        );

        $('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();});

        // SHOW FIRST PHOTO CREDIT
        $('#p_c_0').show();

        if(app.page && app.page.onLoad) {
            app.page.onLoad();
        }
    } 
}

$(document).ready(
    function() {
        app.onLoad();
    }
);