
xhr = {
    script: function(html) {
    	var scriptIndex = 0;
    	var IWScripts = new Array();
    	document.onIWRun = null;
    	document.IWLoaded = true;

    	html = html.replace(/<(\/?)script/gi, "<$1script");
    	var scriptStart = html.indexOf("<script");
    	var scriptEnd = -1;
    	var scriptBody = "";

    	while(scriptStart > -1) {
    		scriptEnd = html.indexOf("</script>")+9;
    		scriptBody = html.substring(html.indexOf(">", scriptStart)+1, scriptEnd - 9);

    		document.onIWComplete = null;
    		try {
    			eval(scriptBody);
    		} catch (e) {
    			window.console.log(e);
    		}
    		if (document.onIWComplete) {
    			IWScripts[scriptIndex] = document.onIWComplete;
    			scriptIndex++;
    		}

    		html = html.substring(0,scriptStart) + html.substring(scriptEnd, html.length);
    		scriptStart = html.indexOf("<script");
    	}

    	if (typeof document.onIWRun == 'function') {
    		document.onIWRun(html);
    	}

    	if (IWScripts.length) {
    		for (var i = 0; i < IWScripts.length; i++) {
    			try {
    				IWScripts[i]( );
    			} catch (e) {
    				window.console.log(e);
    			}
    		}
    	}
    },

    action: function(obj, $container) {
        var action,
            title,
            $this       = typeof obj == "object" ? $(obj) : $(),
            $preloader  = $('div.preloader'),
            $status     = $('<div>');

        if ($.isPlainObject(obj)) {
            action  = obj.action,
            title   = obj.title || action;
        } else {
            action  = (obj.getAttribute != null) && (obj.getAttribute('action') || obj.getAttribute('href') || obj.getAttribute('data-url')),
            title   = (obj.getAttribute != null) && (obj.getAttribute('title') || obj.getAttribute('data-title')) || action;
        }

        if (!$preloader.length) {
            $preloader  = $('<div>')
                            .addClass('preloader')
                            .prependTo('body');
        }

        if ($this.attr('title') !== false && typeof title == 'string') {
            $preloader.show();
            $status.text(title).appendTo($preloader);
        }

        function success(html) {
            var bodyStart   = html.toLowerCase().indexOf("<body>"),
                bodyEnd     = html.toLowerCase().indexOf("</body>");

            if (bodyStart > -1 && bodyEnd > -1)  {
                html = html.substring( bodyStart + 6, bodyEnd );
            }

            xhr.script(html);

            $status.fadeOut('fast', function(){
                if ($preloader.find('div').length) $preloader.remove();
                if ($overlay) $overlay.remove();
            });
        }

        function error() {
            if ($overlay) $overlay.remove();
            $status
                .addClass('e')
                .append('<em>(404)</em>')
                .delay(2000)
                .fadeOut(function(){
                    $(this).remove();
                    if ($preloader.find('div').length) $preloader.remove();
                });
        }

        if ($container) {
            var $overlay = $('<div>')
                            .addClass('xhr-overlay')
                            .prependTo($container);

            function offset() {
                var h   = $container.height(),
                    w   = $container.width();

        		$overlay.css({ width:w, height:h });
            }

            offset();

            $(window).resize(function() {
        		offset();
        	});
        }

        if (!$.isPlainObject(obj) && $this.is('form')) {
    		var options = {
    			type: 'post',
    			url: action,
    			success: function(html) {
    				success(html);
    			},
    			error: function() {
    			    error();
    			}
    		};
    		$this.ajaxSubmit(options);
    	} else {
    		$.ajax({
    			type: 'get',
    			url: action,
    			success: function(html) {
    				success(html);
    			},
    			error: function() {
    			    error();
    			}
    		});
    	}

    	if (!$.isPlainObject(obj) && $this.is('a')) obj.blur();

    	return false;
    },

    refresh: function(url) {
        if (typeof url == 'undefined' || !url) {
            window.location.reload(true);
        } else {
            window.location.href = url;
        }
    }

};


(function($) {
    var Modal = function(options, $this) {
        var self = this;
        var settings = $.extend(this, $.fn.modal.constructor, options);

        if ($this) {
            $this.bind('click', function(e) {
                self.init(this);
                e.preventDefault();
            });
        } else {
            self.init();
        }
    };

    $.modal = function(options) {
         new Modal(options);
    };

    $.fn.modal = function(options) {
        return this.each(function(){
            var $this = $(this);
            if (!$this.data('modal')) {
                var modal = new Modal(options, $this);
                $this.data('modal', modal);
            }
        });
    };

    $.fn.modal.constructor = {
        url: false,
        content: '',
        image: false,
        data: {},
        scroll: 0,
        modal: 1,
        overlay: 1,
        opacity: 0.8,
        view: 1,
        move: 0,
        close: 0,
        container: 'body',
        cache: 0,

        init: function(opener) {
            this.opener = opener || false;
            if (this.url === false && this.content === '') this.url = this.opener.href;

            $(this.opener).addClass('active');

            if (this.$modal) {
                if (!this.$modal.is(':visible')) {
                    if (this.cache) {
                        this.show();
                    } else {
                        this.remove();
                        this.create();
                    }
                } else {
                    this.remove();
                }
            } else {
                this.create();
            }
        },

        create: function(){
            var self = this;

            if (this.url) {
                var $preloader  = $('div.preloader'),
                    title       = this.opener && $(this.opener).attr('title') ? $(this.opener).attr('title') : this.url;

                if (!$preloader.length) {
                    $preloader = $('<div>').addClass('preloader').prependTo('body');
                } else {
                    $preloader.show();
                }

                if (this.$preloader) {
                    this.$preloader.text(title);
                } else {
                    this.$preloader = $('<div>').text(title);
                }

                if (!$preloader.find(this.$preloader).length) this.$preloader.appendTo($preloader).show(); // feautures
            }

            if (this.container == 'body') {
                if (!this.scroll) window.scroll(0, 0);

                this.$modal = $(
                    '<table class="modal' + ( this.scroll ? ' modal-scrollable' : '') + ' modal-view' + this.view + '">' +
                        '<tr>' +
                            '<td class="modal">' +
                                '<table class="modal-wrapper">' +
                                    '<tr>' +
                                        '<td class="modal-wrapper">' +
                                            '<div class="modal-window">' +
                                                '<div class="modal-menu">' +
                                                    '<a class="modal-remove" href="./">x</a>' +
                                                '</div>' +
                                                '<div class="modal-content xhr-container"></div>' +
                                            '</div>' +
                                        '</td>' +
                                    '</tr>' +
                                '</table>' +
                            '</td>' +
                        '</tr>' +
                    '</table>'
                ).hide();
            } else {
                this.$modal = $(
                    '<div class="modal-bind modal-view' + this.view + '">' +
                        '<div class="modal">' +
                            '<div class="modal-spacer"></div>' +
                            '<div class="modal-window">' +
                                '<div class="modal-menu">' +
                                    '<a class="modal-remove" href="./">x</a>' +
                                '</div>' +
                                '<div class="modal-content xhr-container"></div>' +
                            '</div>' +
                        '</div>' +
                    '</div>'
                ).hide();
            }

            if (this.overlay) {
                this.$overlay = $('<div class="modal-overlay"><iframe></iframe></div>');
                this.$overlay
                    .css({ display:'none', opacity:self.opacity })
                    .appendTo('body')
                    .fadeTo('fast', self.opacity);
            }

            this.$modal.appendTo(this.container);

            this.$window = this.$modal.find('table.modal-window');
            this.$content = this.$modal.find('div.modal-content');

            this.$modal.delegate('.modal-remove', 'click', function(e){
                self.remove();
                e.preventDefault();
            });
            this.$modal.delegate('a.modal-reload', 'click', function(e){
                xhr.action(this, self.$content);
                e.preventDefault();
            });

            if (!this.modal) {
                self.docevnt = function(e){
                    if (!(self.opener && self.opener == e.target || $(self.opener).has(e.target).length) && (self.$window.get(0) != e.target && !self.$window.has(e.target).length)) {
                        self.remove();
                    }
                };
                $(document).bind('click', self.docevnt);
            }

            if (this.image) {
                self.content = '<img src="'+this.url+'">';
            }

            if (this.url && !this.image) {
                $.ajax({
                    type: 'get',
                    url: self.url,
                    data: self.data,
                    success: function(html) {
                        var bodyStart   = html.toLowerCase().indexOf("<body>"),
                            bodyEnd     = html.toLowerCase().indexOf("</body>");

                        if (bodyStart > -1 && bodyEnd > -1)  {
                            html = html.substring( bodyStart + 6, bodyEnd );
                        }

                        self.$content.html(html);
                        self.$modal.show();
                        self.$preloader.fadeOut('slow', function(){
                            $(this).remove();
                            if (!$preloader.find('div').length) $preloader.hide();
                        });

                        $('form.validate').validate();
                    },
                    error: function() {
                        self.$modal.remove();
                        if (self.overlay) self.$overlay.hide();
                        self.$preloader
                            .addClass('e')
                            .append('<em>(404)</em>')
                            .delay(2000)
                            .fadeOut(function(){
                                $(this).remove();
                                delete self.$preloader;
                                if (!$preloader.find('div').length) $preloader.hide();
                            });
                    }
                });
            } else {
                self.$content.html(self.content);
                self.$modal.show();
                self.$preloader.fadeOut('slow', function(){
                    $(this).remove();
                    if (!$preloader.find('div').length) $preloader.hide();
                });
            }
        },

        show: function() {
            var self= this;

            this.$modal.show();
            this.overlay && this.$overlay.fadeTo('fast', self.opacity);
            !this.modal && $(document).bind('click', self.docevnt);

            if (this.container == 'body' && !this.scroll) window.scroll(0, 0);
        },

        remove: function() {
            var self= this;

            $(document).unbind('click', self.docevnt);

            if (this.cache) {
                this.$modal.hide();
                this.$overlay.fadeOut('fast', function(){
                  $(this).css({ opacity:self.opacity });
                });
            } else {
                this.$modal.remove();
                this.$overlay.fadeOut('fast', function(){
                  $(this).remove();
                });
            }

            $(this.opener).removeClass('active');
        }
    };
})(jQuery);

(function($) {
    $.fn.validate = function(options) {
        var $fields = this.find('input, select, textarea');

		settings = $.extend($.fn.validate.constructor, options);

        if (this.is('form')) {
            this.find(':submit')
                .unbind('click', settings.submit)
                .bind('click', settings.submit);
        }

        if((this.is('input') || this.is('select') || this.is('textarea')) && (settings.error != undefined)) {
            settings.result($(this), false);
        }

        $fields
            .unbind('keyup', settings.keyup)
            .bind('keyup', settings.keyup)
            .unbind('focusout', settings.focusout)
            .bind('focusout', settings.focusout);

        return this;
    };

    $.fn.validate.constructor = {
        keyup: function(){
            if (this.getAttribute('required') != null) {
                settings.result($(this));
            }
        },

        focusout: function(){
            if (this.getAttribute('required') != null) {
                settings.check(this);
            }
        },

        submit: function(event){
            var $form       = $(this).closest('form'),
                $invalid    = $();

            $form.find('input, select, textarea').each(function(){
                if (this.getAttribute('required') != null) {
                    settings.check(this);
                }
                if ($(this).hasClass('ckeditor') && this.id && typeof CKEDITOR != 'undefined') {
                    var instance = CKEDITOR.instances[this.id];
                    if (instance) {
                        $(this).val( instance.getData() );
                    }
                }
            });

            $invalid = $form.find(':input.invalid');

            $invalid.first().focus();

            if (!$invalid.length) {
                if ($form.hasClass('xhr')) {
                    xhr.action($form.get(0), $form.closest('.xhr-container'));
                } else {
                    $form.submit();
                }
            }
            event.preventDefault();
        },

        result: function($this, valid) {
            var $parent     = $this.parent(),
                $required   = $this.next('span.required'),
                $error      = $required.find('span'),
                msg         = this.error || $this.attr('data-error');
                this.error  = '';

            if (!$required.length) $required = $('<span>').insertAfter($this);

            if (valid === true) {
                $this.removeClass('invalid');
                $required.attr('class', 'required valid').show();
                $error.hide();
            } else if (valid === false) {
                $this.addClass('invalid');
                $required.attr('class', 'required invalid').show();
                if (!$error.length && msg) {
                    $error = $('<span>')
                                .text(msg)
                                .addClass('error')
                                .appendTo($required)
                                .show();
                } else if (msg) {
                    $error.text(msg);
                    $error.show();
                }
            } else {
                $this.removeClass('invalid');
                $required.hide();
            }
        },

        check: function(obj) {
            var self    = this,
                $this   = $(obj),
                valid   = true;

            if ($this.is('input') || $this.is('textarea')) {
                $this.each(function() {
                    var pattern;

                    if ($this.val() === '') {
                        self.result($this, false);
                        return;
                    }

                    if (obj.getAttribute('type') == 'email') {
                        pattern = new RegExp(/^([a-z0-9_\.\-\+]+)@([\da-z\.\-]+)\.([a-z\.]{2,6})$/);
                        if (!pattern.test($this.val())) {
                            self.result($this, false);
                            return;
                        }
                    }

                    if (obj.getAttribute('type') == 'number') {
                        pattern = new RegExp(/^-?[0-9]*(\.[0-9]+)?$/);
                        if (!pattern.test($this.val())) {
                            self.result($this, false);
                            return;
                        }
                    }

                    if (obj.getAttribute('type') == 'url') {
                        pattern = new RegExp(/^(https?:\/\/)?[\da-z\.\-]+\.[a-z\.]{2,6}[#&+_\?\/\w \.\-=]*$/i);
                        if (!pattern.test($this.val())) {
                            self.result($this, false);
                            return;
                        }
                    }

                    if (obj.getAttribute('type') == 'password') {
                        var $pair = $this.closest('form').find('input[type=password]').not(obj);
                        if ($pair.length && $pair.val() != '' && $pair.val() != $this.val()) {
                            self.result($this, false);
                            return;
                        } else if ($pair.val() != '') {
                            self.result($pair, true);
                        }
                    }

                    if ($this.attr('pattern')) {
                        pattern = new RegExp($this.attr('pattern'));
                        if (!pattern.test($this.val())) {
                            self.result($this, false);
                            return;
                        }
                    }

                    self.result($this, true);
                });
            }
        }
    };
})(jQuery);


$(function(){
    $('a.modal').modal();

    $('a.modal-image').modal({ image: true, modal: 0, scroll: 0 });

    $('form.validate').validate();

    $('a.xhr').live('click', function(event){
        var container = $(this).attr('data-container');
        xhr.action(this, $(container));

        event.preventDefault();
        return false;
    });

    $("a[rel^=gallery]").prettyPhoto({
        // slideshow:5000, autoplay_slideshow:true
    });

    /*
    $('#banner').each(function(){
        var $banner = $(this),
            $frames = $banner.find('div.frames div.frame'),
            delay = 1000;
        $frames.each(function(){
            $(this).delay(delay).fadeIn();
            delay *= 2;
        })
    });
    */

    if ($.fn.nivoSlider) {
        $('#banner div.frames').nivoSlider({
            effect: 'fold',
            directionNav: false,
            controlNav: false,
            keyboardNav: false,
            pauseOnHover: false,
            beforeChange: function() { },
            afterChange: function() {
                if ($('#banner div.frames').data('nivo:vars').currentSlide == 2) {
                    $('#banner div.frames').data('nivo:vars').stop = true;
                    $('#banner div.intro').fadeIn('slow');
                }
            }
        });
    }

    /* RELOAD CAPTCHA */
    $('a.captcha').live('click', function() {
    	var dt = new Date();
    	var im = $('img.captcha');
    	im.attr('src', im.attr('src').replace(/\?(.*)$/, '?'+dt.getTime() ));
    	return false;
    });

});



