/**
 * Core of Marche Application
 *
 * @author lukasz.olszewski@iware.pl
 * @version 0.1
 */
var marcheApp = window.marcheApp || {};
/**
 * Start of application
 * @param config {Object}
 */
marcheApp.init = function(config){

    config = config || {};
    /**
     * @type {string}
     */
    this.ajaxUrl = config.ajaxUrl || '';
    /**
     * @type {string}
     */
    this.imgUrl = config.imgUrl || '';
    /**
     * @type {string}
     */
    this.ajaxOpinion = config.ajaxOpinion || '';
    /**
     * @type {boolean}
     */
    this.debug = config.debug || false
    /**
     *  Maps Url
     *  @type {string}
     */
    this.maps = config.maps || '';
    /**
     * @type {array}
     */
    this.backgrounds = config.backgrounds || [];
    /**
     * @type {string}
     */
    this.facebook = config.facebook || "";
	/**
	 * @type {string}
	 */
	this.baseUrl = config.baseUrl || "";
    this.seo = config.seo;

    for(var package in this){
        this.hasOwnProperty(package) && this[package]['init'] && this[package].init();
    }

};
/**
 * Get or set element from cache
 *
 * @param element {String}
 * @param selector {String|Object}
 *
 * @return {jQuery}
 */
marcheApp.elementCache = (function(){

    var elements = {};

    return function(element, selector){

        if (elements[element] === undefined){
            elements[element] = $(selector);
        }

        return elements[element];
    }
})();
/**
 * Utils
 */
marcheApp.utils = {};

marcheApp.utils.init = function(){
    this.fixIe();
}

marcheApp.utils.detectCSS3 = (function(){

   var div = document.createElement('div'),
      vendors = 'Khtml Ms O Moz Webkit'.split(' '),
      len = vendors.length,
      cache = {};

   return {
       isExist : function(prop) {
           if ( prop in div.style ) return true;

           prop = prop.replace(/^[a-z]/, function(val) {
               return val.toUpperCase();
           });

           while(len--) {
               if ( vendors[len] + prop in div.style ) {

                   return true;
               }
           }
           return false;
       },
       checkStyle : function(styl){

           if (!(styl in cache)){
                cache[styl] = this.isExist(styl);
           }

           return cache[styl];
       }
   }
})();
/**
 * Fuckin' IE
 *
 */
marcheApp.utils.fixIe = function(){

   if(!Array.indexOf){
	    Array.prototype.indexOf = function(obj){
	        for(var i=0,max = this.length; i < max; i++){
	            if(this[i] === obj){
	                return i;
	            }
	        }
	        return -1;
	    }
	}
    if (!window['console']){
        window['console'] = {};
        window['console'].log = function(){

        }
    }
}
marcheApp.utils.IEVersion = (function(){
  var rv = -1;
  if (navigator.appName === 'Microsoft Internet Explorer')
  {
    var ua = navigator.userAgent;
    var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
    if (re.exec(ua) != null)
      rv = parseFloat( RegExp.$1 );
  }
  return rv;
})();
/**
 * Define Types
 *
 */
marcheApp.type = {};
/**
 * Callback with context
 *
 * @param callback {function}
 * @param context {object|string}
 */

marcheApp.type.Runnable = function(callback, context){

    this.callback = callback;

    this.context = context || window;
    this.args = Array.prototype.slice.call(arguments,2);
};
/**
 * Run callback
 *
 */
marcheApp.type.Runnable.prototype.run = function(){


    if (typeof this.context === 'string'){
        var element = $(this.context);
        this.context = element.children('a');
    }

   // console.log(this.context);

    this.callback.apply(this.context, this.args);
};

/**
 * Package Animation
 *
 */
marcheApp.animation = {};

marcheApp.animation.galleryContent = (function(){

    var gallery = this.elementCache("gallery","#gallery");

    return {
        show : function(callback){

            gallery.show().stop().animate({width : 560}, 'slow', callback);
        },
        hide : function(callback){
            $('.galleryActive')
                .removeClass('galleryActive');
            gallery.hide().stop().animate({width : 0}, 'fast', callback);
        },
        isShow : function(){
            return gallery.is(':visible');
        }
    }

}).call(marcheApp);

/**
 * Fade out big photo
 *
 * @param callback {function}
 */
marcheApp.animation.hidePhoto = function(callback){
    //alert(typeof callback);
    this.fadeOut('fast');
    callback && (typeof callback === 'function') && callback.call(this);

};
/**
 * Fade in big photo
 *
 * @param callback {function}
 */
marcheApp.animation.showPhoto = function(callback){

    this.fadeIn('slow');

    callback && (typeof callback === 'function') && callback.call(this);
};
/**
 *
 * @param callback
 */
marcheApp.animation.photo = (function(){

    var scroll = null, that = this;

    return {
        show : function(id){
            var index = $(".galleryItem").index($('#' + id));
            scroll = $('#galleryPhotoScroll');
            //scroll || (scroll = that.elementCache('galleryPhotoScroll','#galleryPhotoScroll'));
            scroll.css({left : (490 * parseInt(index)) * -1});

        }
}

}).call(marcheApp);



marcheApp.animation.content = (function(){

    var content = this.elementCache('contentPage','#contentPage'), app = this;

    return {
        show : function(){
            that = this;
            content.show().animate({'width' : '418'}, 200, function(){
             $(this).addClass('animated');
             app.animation.pageInner.fadeIn.call($('.pageInner'),content);
             app.animation.checkSubMenu.apply(that);

           });
        },
        hide : function(callback){
            var context = this;
            content.animate({'width' : '0'}, 200, function(){
                $(this).hide().removeClass('animated');
                app.animation.uncheckSubMenu.apply(content);
                callback && callback.call(context);
            });
        },
        isShow : function(){
            return content.hasClass('animated');
        },
        showFirstTab : function(){
            $('.tabs:first',content).show();
        },
        showGallery : function(){
            $('#pageGaleria',content).show();
        }
    }
}).call(marcheApp);

/**
 * Check (Fade) active Main Menu
 *
 */
marcheApp.animation.checkMainMenu = function(){
    marcheApp.animation.uncheckMainMenu();
    if (marcheApp.utils.IEVersion > 8 || marcheApp.utils.IEVersion === -1){
        $(this).prev('span.activeMenu').fadeIn("slow");
    } else {
        $(this).prev('span.activeMenu').show();
    }
    marcheApp.event.stars.check(this);
};
/**
 * Uncheck all main menu
 */
marcheApp.animation.uncheckMainMenu = (function(app){
    var rootMenu = app.elementCache('rootMenu','.menu ul');

    return function(){
        if (marcheApp.utils.IEVersion > 8 || marcheApp.utils.IEVersion === -1){
        $('.activeMenu',rootMenu).fadeOut("fast");
        } else {
            $('.activeMenu',rootMenu).hide();
        }
        marcheApp.event.stars.uncheck(this);
    }

})(marcheApp);
/**
 * Check (Fade) active Submenu
 *
 */
marcheApp.animation.checkSubMenu = function(){

    var rootElement = $(this).parents('li'),
    rootSubMenu = marcheApp.elementCache('rootSubMenu',rootElement.parent('ul'));
    if (marcheApp.utils.IEVersion > 8 || marcheApp.utils.IEVersion === -1){
        $('.activeSubMenuWaraper',rootSubMenu).fadeOut("fast");
        rootElement.children('.activeSubMenuWaraper').fadeIn("slow");
    } else {
        $('.activeSubMenuWaraper',rootSubMenu).hide();
        rootElement.children('.activeSubMenuWaraper').show();
    }

};
/**
 * Uncheck submenu
 *
 */
marcheApp.animation.uncheckSubMenu = function(){
    var activeSubMenu = marcheApp.elementCache('activeSubMenuWaraper','.activeSubMenuWaraper');

    $(activeSubMenu).hide();

};

marcheApp.animation.submenu = (function(){

    return {
        show : function(){
            var submenu = $(this);
            marcheApp.animation.submenu.hide(function(){
                submenu.show().stop().animate({'width' : '250'}, 300, (function(a){
                    return function(){

                    }
                })(marcheApp.animation));
            });
        },
        hide : function(callback){
            var submenus = marcheApp.elementCache('submenus','.submenu').filter(':visible');
            if (submenus.length === 0){
                callback.apply(this);
            } else {
                submenus.filter(':visible').animate({'width' : '0'}, 50, function(){

                        $(this).hide();

                        callback.apply(this);

                });
            }
        },
        isShow : function(submenu){
             return submenu.hasClass('animated');
        }
    }

})();
/**
 * Animate submenu
 *
 */
marcheApp.animation.showSubMenu = function(){

    var submenu = $(this);

    marcheApp.animation.hideSubMenu(function(){
        submenu.show().animate({'width' : '250'}, 300, (function(a){
            return function(){

            }
        })(marcheApp.animation));

    });

};
/**
 * Hide submenu
 *
 * @param callback {function}
 */
marcheApp.animation.hideSubMenu = function(callback){

    var submenus = marcheApp.elementCache('submenus','.submenu').filter(':visible');

    if (submenus.length === 0){
        callback.apply(this);
    } else {
        submenus.filter(':visible').animate({'width' : '0'}, 50, function(){

                $(this).hide();

                callback.apply(this);

        });
    }

};
/**
 * Is submenu aminated
 * @param submenu {jQuery}
 * @return {boolean}
 */
marcheApp.animation.isShowSubMenu = function(submenu){

    return submenu.hasClass('animated');
};


marcheApp.animation.spout = (function(){

    var spout = null;

    return {
        hide : function(){
            spout || (spout = $('.spout'));
            spout && spout.css({'z-index' : '0'});
        },
        show : function(){
            spout && spout.css({'z-index' : '3'});
            spout = null;
        }
    }

}).call(marcheApp);
/**
 * FadeIN i FadeOut dla Contentu
 *
 */
marcheApp.animation.pageInner = (function(){
    var that = this;
    return {
        fadeIn : function(callback){
            if (that.utils.IEVersion > 8 || that.utils.IEVersion === -1){
                if (that.utils.detectCSS3.checkStyle('transition')){
                    $(this).css('opacity',1);
                    (callback && callback.run && callback.run())
                } else{
                    //$(this).css('opacity',1);
                    $(this).animate({'opacity' : 0},'slow', function(){
                                callback && callback.run && callback.run();
                            });
                }
            } else {
                (callback && callback.run && callback.run())
            }
        },
        fadeOut : function(callback){
            if (that.utils.IEVersion > 8 || that.utils.IEVersion === -1){
                //$(this).css('opacity',0);
                $(this).animate({'opacity' : 0},'slow', callback);
            } else {
                (callback && callback());
            }

        }
    }

}).call(marcheApp);
/**
 * Rotate Backgrounds
 *
 */
marcheApp.animation.backgrounds = (function(){
    var loadBackgrounds = [], index;
    return {
        addBg : function(element){
            loadBackgrounds.push(element);
        },
        init : function(){
            setTimeout(this.rotate, 500);
           setInterval(this.rotate, 5000);


        },
        rotate : function(){
			//console.log(loadBackgrounds);
            if (loadBackgrounds.length > 0){
                if (typeof index === "undefined"){
                    index = 0;
                    loadBackgrounds[index].fadeIn('slow');
                } else if (loadBackgrounds.length > 1) {
                 //   console.log(index);
                    loadBackgrounds[index].fadeOut('slow');
                    index = (++index) % loadBackgrounds.length;
                    loadBackgrounds[index].fadeIn('slow');
                }
            }
        }
    }
}).call(marcheApp);

/**
 * Event's
 */
marcheApp.event = {};

marcheApp.event.init = function(){

    if (!("orientation" in window)){
      $(window)
        .bind('resize', this.resizeWindow)
        .trigger('resize');
    } else {
        this.resizeWindow();
    }

    //var h = $('.wrapperMenu').height();
    //$('.page').css('height', 550 );

    $("#galleryBack")
            .live('mousedown', this.move.bindContent)
            .live('mouseup', this.move.unbindContent)
            .live('click', function(event){
                //event.preventDefault();
            });
    $("#galleryPhoto").
            live('touchstart', this.movePhoto.init).
            live('touchend ', this.movePhoto.destroy)
            .live('click', function(event){
                event.preventDefault();
            });

    //No cache
    var menu_wydarzenia = marcheApp.elementCache("menu_wydarzenia","#menu_wydarzenia");

    menu_wydarzenia.delegate('#eventsNew', 'click', this.events.clickShowNew);
    menu_wydarzenia.delegate('#eventsHistory', 'click', this.events.clickShowHistory);

    this.subMenuClick();
    this.mobile.init();
//    this.languages.init();
    marcheApp.event.photo.init();

};

marcheApp.event.languages = (function(){
    var that = this;
    return {
        init : function(){
            $('.lang').bind('click', this.changeLanguage);
        },
        changeLanguage : function(event){
            event.preventDefault();
            var href = $(this).attr('href');
            document.location = href + document.location.hash;

            //alert(lng);
        }
    }
}).call(marcheApp);


marcheApp.event.events = (function(){
    var that = this;
    return {
        showNew : function(){
            var eventsNew = $(".eventsNew"), eventsHistory = $(".eventsHistory");

            eventsHistory.hide().css({opacity: 0});
            eventsNew.show().css({opacity: 1});

            //console.log(eventsNew);
        },
        showHistory : function(){
            var eventsNew = $(".eventsNew"), eventsHistory = $(".eventsHistory");

            eventsNew.css({opacity: 0}).hide();
            eventsHistory.show().css({opacity: 1})

            console.log(eventsHistory);
        },
        clickShowNew : function(event){
            event.preventDefault();
            that.view.clickedMenuPage.call(window['eventsNew'] || document.getElementById('eventsNew'));
            that.event.events.showNew();
        },
        clickShowHistory : function(event){
            event.preventDefault();
            that.view.clickedMenuPage.call(window['eventsHistory'] || document.getElementById('eventsHistory'));
            that.event.events.showHistory();
        }

    }

}).call(marcheApp);


marcheApp.event.subMenuClick = function(){
    var photoMenu = marcheApp.elementCache("photoMenu",".photoMenu");

    photoMenu.each(function(){
        $(this).bind('click', (function(href){
            return function(){
                document.location = href;
            }
        })($(this).next('.subMenuPosition').children('a').attr('href')));
    });
    //photoMenu
}
/**
 *  Move gallery
 *
 */
marcheApp.event.move = (function(){

    var contentPage = this.elementCache("contentPage","#contentPage"),
    gallery = this.elementCache("gallery","#gallery"),
    that = null, app = this;

    return {
        base : 800,
        left : -283,
        right : 278,
        current : 278,
        bindContent : function(event){
            that || (that = marcheApp.event.move);
            marcheApp.animation.spout.hide();
            event.preventDefault();

            contentPage.removeClass('animateToLeft');
            gallery.removeClass('animateToLeft');

            $(document).bind('mousemove', function(e){
                var x, y, orig = e.originalEvent;
                x = orig.clientX;
                y = orig.clientY;

                //var style = {left: x-$(contentPage).width()};
                var style = {left : x - that.base}
                contentPage.css(style);
                gallery.css(style);
            });

        },
        unbindContent : function(){
            that || (that = marcheApp.event.move);

            $(document).unbind('mousemove');

            that.current === that.left ? that.current = that.right : that.current = that.left;
            contentPage
                .addClass('animateToLeft')
                .css({'left':that.current});
            gallery
                .addClass('animateToLeft')
                .css({'left':that.current});

            if (that.current === that.right) {
                app.animation.galleryContent.hide();
                app.animation.spout.show();
            } else {
                app.animation.galleryContent.show();
            }
        },
        contentToLeft : function(){
            that || (that = marcheApp.event.move);
            that.current = that.left;
            this.scrollContent(that.current, marcheApp.animation.spout.hide);
        },
        contentToRight : function(){
            that || (that = marcheApp.event.move);
            that.current = that.right;
            this.scrollContent(that.current, marcheApp.animation.spout.show);

        }, scrollContent : function(position,callback){
            contentPage
                .addClass('animateToLeft')
                .css({'left':position});
            gallery
                .addClass('animateToLeft')
                .css({'left':position});
            $("#pageGaleria").tinyscrollbar();
            callback && typeof callback === 'function' && callback();
        }
    }

}).call(marcheApp);
/**
 *
 */
marcheApp.event.movePhoto = (function(){

    var left = 0, touch = undefined;

    return {
        init : function(event){

            if (event.originalEvent && (event.originalEvent.touches || event.originalEvent.changedTouches)){
                touch =  event.originalEvent.touches[0] || event.originalEvent.changedTouches[0];
            }


            var gallery = $("#galleryPhotoScroll"),xx;


            gallery.removeClass('animateToLeft');

            if(touch===undefined){
                    xx = event.clientX;
                }else{
                    xx = touch.pageX;
                }

            elementX =  xx - left;

            $(gallery).focus(function(event){
                event.preventDefault();
            });

            $(document).bind('touchmove mousemove', function(e){
                //var left = parseInt(gallery.css('left'));

                var touch = undefined;
                if (e.originalEvent && (e.originalEvent.touches || e.originalEvent.changedTouches)){
                   touch =  e.originalEvent.touches[0] || e.originalEvent.changedTouches[0];
                }
                var x, y, orig = e.originalEvent;

                if(touch === undefined){
                    x = orig.clientX;

                }else{
                    x = touch.pageX;
                }


                left = (x - elementX);

                var style = {left: x-$(gallery).parent().width()};
                //var left = parseInt(gallery.css('left'));
                gallery.css({left : left});

            });
        },
        destroy : function(){
            var gallery = $("#galleryPhotoScroll");
                 $(document).unbind('mousemove').unbind('touchmove');
                gallery.addClass('animateToLeft');


        }
    }

}).call(marcheApp);

/**
 * Event Resize Window
 *
 */
marcheApp.event.resizeWindow = (function(){
    //Private
    var height = 0, margin = 0, submenus = null, body = null;

    return function(){
        height = $(document).height();
        //alert(height);
        submenus = marcheApp.elementCache('submenus','.submenu');
        body = marcheApp.elementCache('body','.body');
        margin = (height/2) - 48;
        body.css('height',height);
        submenus.css('height',height).css('margin-top','-' + margin + 'px');
    }

})();
/**
 * Event for mobile device
 *
 */
marcheApp.event.mobile = (function(){
    var app = this,mobile = {
        init : function(){
            if ("orientation" in window){
                $('head').append('<meta name="viewport" content="width=1000, userscalable=no" />');
                alert($('head').html());
                this.orientation();
            }
            //alert($(window).height() + location.reload)
        },
        orientation : function(){
                window.addEventListener("orientationchange",
                    function(){
                        alert(window.innerHeight);
                       // location.reload();
                        //alert($(window).height())
//                        switch(window.orientation) {
//                            case 90:
//                            case -90:
//                            //alert("landscape");
//                            app.event.resizeWindow();
//                            location.refresh();
//                        break;
//                        default:
//                            //alert("portrait");
//                            app.event.resizeWindow();
//                        }
                    }, false);
        }

    };

    return mobile;
}).call(marcheApp);
/**
 * Only show photo
 *
 */
marcheApp.event.showGalery = (function(){

    var img = this.elementCache("showPhoto","#showPhoto");

    return function(callback,id){
        var that = this;

        this.animation.hidePhoto.call(img,function(){

            that.view.photoGalery(id);
            that.animation.showPhoto.call(img,function(){
                callback && callback.run();
            });
        })
    }

}).call(marcheApp);

/**
* Event click on photo of gallery
*
* @param callback {marcheApp.type.Runnable}
* @param id {String}
*
*/

marcheApp.event.clickGalery = (function(){

    var img = this.elementCache("showPhoto","#showPhoto"),
    gallery = this.animation.galleryContent,
    that = this;

    return function(callback,id){

        if (gallery.isShow()){
               that.event.showGalery.call(that,callback, id);
        } else {
            that.animation.content.showGallery();
            that.event.move.contentToLeft();
            gallery.show(function(){
                that.event.showGalery.call(that,callback, id);
            });
        }
    }

}).call(marcheApp);


/**
 * Event click on Main Menu
 *
 * @param nextOperation {marcheApp.type.Runnable}
 *
 */

marcheApp.event.clickMainMenu = function(nextOperation){

    var animation = marcheApp.animation,
    submenu = this.next('.submenu'),
    parent = this.parent();

    if (!parent.hasClass('active')) {
        marcheApp.animation.content.hide.call(this, (function(s,p,a,n){

            return function(){
                var app = marcheApp;
                if (a.content.isShow.call(this,s)){
                    a.checkMainMenu.apply(this);

                } else {
                    a.submenu.show.apply(s);

                }
                a.checkMainMenu.call(this);
                $('.menuItem').removeClass('active');
                p.addClass('active');
                //alert();
                // Strategiczny TRY CATCH - FOR IE
                try{
                    ((n !== null) && n.run()) ||
                    app.appExtends.seo.set($(this).text().trim() + " - " + app.appExtends.seo.getDefault().title).use();
                }catch(e){

                }
            }

        }).call(this, submenu, parent, animation, nextOperation));
    } else {
        if (nextOperation){
           nextOperation.run();
        }
    }

};
/**
 * Click on element of submenu
 *
 * @param nextOperation {marcheApp.type.Runnable}
 *
 */
marcheApp.event.clickSubMenu = function(nextOperation){

    // event.preventDefault();
    var that = this,app = marcheApp, animation = app.animation;

    if (animation.content.isShow()){
        app.animation.checkSubMenu.apply(that);
        animation.pageInner.fadeIn.call($('.pageInner'));
    } else {
        animation.content.show.apply(that);
    }
    app.animation.content.showFirstTab();

    app.appExtends.scroll();
    app.appExtends.scrollFixMenu();
    app.appExtends.maps();
    nextOperation && nextOperation.run();
};
/**
 * Click on element of page submenu
 *
 * @param nextOperation {marcheApp.type.Runnable}
 *
 */

marcheApp.event.clickPageMenu = function(nextOperation){

     var app = marcheApp;

     app.view.clickedMenuPage.call(this);

     $('.tabs').hide();

     $('#' + $(this).attr('rel')).show();


     app.event.move.contentToRight();
     app.animation.galleryContent.hide();
     app.animation.spout.show();
    //app.appExtends.init();
     app.appExtends.scroll();
     app.appExtends.scrollFixMenu();
     app.appExtends.maps();

     (nextOperation && nextOperation.run());// || app.appExtends.seo.set($(this).text().trim() + " - " + app.appExtends.seo.getCurrent().title).use();
};


marcheApp.event.stars = (function(){
   var stars = {
       hoverIn : function(){
            $(this)
                .find('.star').addClass('startShow');
       },
       hoverOut : function(){
            $(this)
                 .find('.star').removeClass('startShow');
       },
       check : function(obj){
           console.log(obj);
          $(obj).unbind('mouseleave').unbind('mouseenter');
           $('.startShow').removeClass('startShow');
           this.hoverIn.call(obj);
       },
       uncheck : function(obj){
           this.hoverOut.call(obj);
           this.init();
       },
       init : function(){
            $(".menuItem > a").unbind('mouseleave').unbind('mouseenter').mouseenter( this.hoverIn).mouseleave(this.hoverOut);
       }
   }
   stars.init();
   return stars;
})();


marcheApp.event.opinion = (function(){

    var app = this, obj = {
        sendForm : function(form){
            app.model.insertOpinion.call(window['pageZobaczOpinie'] || document.getElementById('pageZobaczOpinie'),$(form).serializeArray(),
                    marcheApp.controller.generateView
                    ,function(){

            },function(){
                        alert('view');
                    });
        }
    }

    return obj;
}).call(marcheApp);


marcheApp.event.photo = (function(){

    return {
        init : function(){
//            alert('init PHOTO');
//            $("#contentPage").delegate(".galleryItem img","click",function(){
//                alert('dsdsdsds');
//            });
        },
        load : function(event){
            alert('load');
        }
}

}).call(marcheApp);

marcheApp.appExtends = {};

marcheApp.appExtends._init = function(){

    var content = marcheApp.elementCache('contentPage','#contentPage'), that = this;
    that.scroll();
    that.scrollFixMenu();
    that.maps();
};

marcheApp.appExtends.scroll = function(){
    $('#pageDescription, #pageMenu, #pageGaleria, #pageOpinie').tinyscrollbar();
};


marcheApp.appExtends.scrollFixMenu = function(){
    var length = $('.menuPage li',$("#contentPage")).length, width = 0;
    if (length < 2) return;
    width = parseInt($('.menuPage',$("#contentPage")).width());
    $('.menuPageOther').css({'width' : 335  - width});
};

marcheApp.appExtends.maps = function(){
    if ($("#mapka").length === 0) return;

    try{
        if (typeof ExmapsGoogle === 'undefined'){
            var script = document.createElement("script");
            script.type = "text/javascript";
            script.src = marcheApp.maps;
            document.body.appendChild(script);
        } else{
            ExmapsGoogle.init && ExmapsGoogle.init();
        }
    }catch(e){
        console.log(e);
    }
}

marcheApp.appExtends.form = (function(){

    $.fn.formFocus = function(callback) {
        var element = [], form = document.forms['add_opinion'];
        return this.find("input, textarea").each(function() {
            var value = this.value;
            if ($(this).attr('type') === 'submit'){
                $(this).bind('click',function(event){
                        event.preventDefault();
                        var error = false;
                        for(var i = 0, max = element.length; i < max ; i++){
                            if (element[i].obj.value === element[i].value || element[i].obj.value === ''){
                                $(element[i].obj).addClass('emptyElement').next('.errorInput').show();
                                error = true;
                            }
                        }
                        if (error){
                            setTimeout(function(){
                                $('.errorInput').hide();
                                $('.emptyElement').removeClass('emptyElement');
                            },3000);
                            return false;
                        }

                        callback && callback.call(marcheApp, form);
                });
            } else {
                if ($(this).attr('type') === 'text' || this.nodeName === 'TEXTAREA' ){
                    element.push({obj : this, value : value});
                    $(this).bind('focus',function(){
                        $(this).removeClass('input-nowrite').addClass('input-write');
                        if (this.value === value){
                            this.value = '';
                        }
                    }).bind('blur',function(){
                        $(this).removeClass('input-write').addClass('input-nowrite');
                        if (this.value === ''){
                            this.value = value;
                        }
                    });
                }
            }
        });
    };

    var obj = {
        focus : function(selector){

            $(selector).formFocus(marcheApp.event.opinion.sendForm);
        },
        init : function(){
            var that = this;
            $('#pageZobaczOpinie').livequery(function(){
                that.focus(this);
            });
        }
    }
    obj.init();
    return obj;

})();


marcheApp.appExtends.seo = (function(){

    var title, description, keywords, seoDefault, obj = {

        use : function(){
            !seoDefault && (seoDefault = marcheApp.seo);
            if (marcheApp.utils.IEVersion === -1){
                (title && $("title").html(title)) || $("title").html(seoDefault.title);
                (description && $("description").html(description)) || $("description").html(seoDefault.title);
                (keywords && $("keywords").html(keywords)) || $("keywords").html(seoDefault.title);
            }
            return this;
        },
        set : function(t,d,k){
            console.log('set',t,d,k);
            title=t;
            description = d;
            keywords=k;
            return this;
        },
        getDefault : function(){
            !seoDefault && (seoDefault = marcheApp.seo);
            return seoDefault;
        },
        getCurrent : function(){
            return {
                title : $("title").text(),
                description : $("description").text(),
                keywords : $("keywords").text()
            }
        }
    }
    return obj;
})();

marcheApp.model = {};

marcheApp.model.init = function(){

};

marcheApp.model.getData = function(path,successCallback,errorCallback,callback){
    var page = marcheApp.elementCache('page','.page');

    marcheApp.animation.pageInner.fadeOut.call(page, function(){
        $.ajax({
            url : marcheApp.ajaxUrl,
            type : 'POST',
            data : {'path' : path},
            contextObject : this,
            success : function(){
                successCallback.apply(this, [callback].concat(arguments));
            },
            error : errorCallback
        })
    }
    );
};

marcheApp.model.insertOpinion = function(data,successCallback,errorCallback,callback){

        $.ajax({
            url : marcheApp.ajaxOpinion,
            type : 'POST',
            data : data,
            contextObject : this,
            success : function(){
                successCallback.apply(this, [callback].concat(arguments));
            },
            error : errorCallback
        });

};


marcheApp.view = {};

marcheApp.view.init = function(){
    var that = this;
    $(window).bind('load',function(){
        that.backgrounds.init();
        that.facebook.draw();
    });
}
/**
 * Draw content
 * @param data {string}
 * @param callback {function}
 */
marcheApp.view.drawContent = (function(m){

    var context = {},page = m.elementCache('page','.page');

    context.response = m.elementCache('contentPage','#contentPage').find('.page');//.get(0);
    context.gallery = m.elementCache('gallery','#gallery').find('.galleryInner');//.get(0);
    context.menu_wydarzenia = m.elementCache("menu_wydarzenia","#menu_wydarzenia");
    context.pageZobaczOpinie = '#pageZobaczOpinie';

    var fastInner = function(element, data){

        if (typeof element  === 'string'){
            $(element).html(data);
            return element;
        } else
        if (element instanceof jQuery){
            element.html(data);
            return element;
        } else {
            clone = element.cloneNode(true);

            clone.innerHTML = data;

            element.parentNode.replaceChild(clone, element);

            return clone;
        }
    }


    return function(elements,callback){


        if ("seo" in elements){

            marcheApp.appExtends.seo.set(elements.seo.title, elements.seo.description,elements.seo.keywords);

        } else marcheApp.appExtends.seo.set();

        marcheApp.appExtends.seo.use();

        for(var key in elements){

            if (elements[key] != null){
                elements.hasOwnProperty(key) && context[key] && (context[key] = fastInner(context[key],elements[key]));
            }
        }



        marcheApp.animation.pageInner.fadeIn.call(page,callback);
    }

}(marcheApp));
/**
 * Show big photo
 *
 * @param name {string}
 */
marcheApp.view.photoGalery = (function(){
    var content = marcheApp.elementCache('contentPage','#contentPage'), img = marcheApp.elementCache("showPhoto","#showPhoto"),
    prev = null ,next = null, url = '';

    return function(name){

        //return false;
        if (url === '') url = marcheApp.imgUrl;


        prev = $('#prevPhoto');
        next = $('#nextPhoto');

          var element = $("#" + name), parent = element.parent(),
          prevLink = parent.parents('.photo').prev().find('a').attr('href'),
          nextLink = parent.parents('.photo').next().find('a').attr('href');
          $('.galleryActive').removeClass('galleryActive');
          element.children("img").addClass('galleryActive');

          if (prevLink) {
            prev.attr('href',prevLink).css({'display' : 'block'}).css({'display' : 'block'});
          } else {
              prev.css({'display' : 'none'});
          }

          if (nextLink) {
              next.attr('href',nextLink).css({'display' : 'block'});
          } else {
              next.css({'display' : 'none'});
          }

          marcheApp.animation.photo.show(name);
    }

})();
/**
 * Draw backgrounds
 *
 */
marcheApp.view.backgrounds = (function(){
    var that=this, backgrounds,  d = document, nodeBgs = window['backgrounds'] || d.getElementById('backgrounds');
    return {
        init : function(){
            backgrounds = marcheApp.backgrounds;

            for(var bg in backgrounds){
                backgrounds.hasOwnProperty(bg) && this.drawBackgrounds(backgrounds[bg]);
            }
            that.animation.backgrounds.init();
        },
        drawBackgrounds :  function(background){
			// Path to cache image
			// img/size/o/folders_your_image_is_in-your_image.jpg/w/240/h/160/m/auto
			var imagesUrl = marcheApp.baseUrl+"/img/size/o/"+background.src+"/w/"+($(window).width()+200)+"/h/"+($(window).height()+200)+"/m/auto",
			banerUrl = marcheApp.baseUrl+background.baner;

            $(nodeBgs).append($("<div id='"+background.id+"' \n\
				class='background-image' style='background: transparent url("+encodeURI(imagesUrl)+") \n\
				no-repeat center center; width: "+$(window).width()+"px; height: "+$(window).height()+"px;'>\n\
				\n\
				<div class='baner' style='position:absolute;right:0px;bottom:30px;'><img src='"+banerUrl+"'/></div>\n\
				\n\
				</div>"));
            that.animation.backgrounds.addBg($("#"+background.id));
        },
        loadBackground : function(){
//              var docHeight = $(document).height(),maxHeight;
//              (docHeight < this.height) && (maxHeight = (this.height - docHeight) / 3);
//              maxHeight && (this.style.top = "-"+maxHeight+"px");


              $($(this)).replaceWith("<div id='"+this.id+"' class='background-image' style='background: transparent url("+encodeURI(this.src)+") no-repeat center center; width: "+window.innerWidth+"px; height: "+window.innerHeight+"px;'></div>");

              //$();


        }
    }
}).call(marcheApp);
/**
 * Draw facebook
 *
 */
marcheApp.view.facebook = (function(){
    var that=this;
    return {
        draw : function(){
          if (that.facebook === "") return;

          var fb = window['facebook'] || document.getElementById('facebook');
           fb.innerHTML += that.facebook;
		   $(fb).hover(
				function () {

					$(this).clearQueue();
					$(this).animate({
						right: "0px"
					}, 1000 );

				},
				function () {
					$(this).animate({
						right: "-300px"
					}, 1000 );
				}
				);

        }
    }

}).call(marcheApp);

/**
 * Redraw checked Menu
 */
marcheApp.view.clickedMenuPage = function(){

   // console.log(this);

    var parent = $(this).parents('.menuPage'), elLeft = $('.activeMenuPageLeft', parent),
        elRight = $('.activeMenuPageRight', parent);

    $('.activeMenuPage', parent).removeClass('activeMenuPage');
    $(this).parent()
        .before(elLeft)
        .after(elRight)
        .addClass('activeMenuPage');

};

marcheApp.controller = {};

/**
 * Current path
 *
 */
marcheApp.controller.path = (function(){
   // Private
   var path = '/';

   return {
       setPath : function(p){
           path = p;
       },
       getPath : function(){
           return path;
       }
   }
})();

marcheApp.controller.init = function(){

    if ($.address === undefined)
        throw "jQuery Address is must be requirer";

    $.address.change(this.bootstrap);
    $(window).trigger('change');

};

marcheApp.controller.bootstrap = function(){

    var address = $.address.pathNames();

    marcheApp.controller.path.setPath($.address.path());

    marcheApp.controller.run(address);

};

/**
 * Run page
 *
 * @param paths {Array}
 * @return void
 */
marcheApp.controller.run = (function(e,m){

        var route = [
            e.clickMainMenu,  /* #!/action1   */
            e.clickSubMenu,   /* #!/action1/action2   */
            e.clickPageMenu,  /* #!/action1/action2/action3   */
            e.clickGalery     /* #!/action1/action2/action3/id   */
        ],
        loaded = [],
        model = m.getData,
        content = marcheApp.elementCache('contentPage','#contentPage');

        return function(paths){


            marcheApp.appExtends.seo.set();

            if (!paths.length) return 0;

            var runnables = null, submenu = false;


            for(var i=paths.length -1,max = 0; i >= max; i--){
                //Akcja nie zdefiniowana
                if (!route[i]){
                    throw 'Action is not defined ' + paths[i];
                }
                //Czy dana akacja została już wcześniej wykonana, jeśli tak to ją pomijamy.
                if (loaded.indexOf(paths[i]) !== -1) continue;

                // Czy akcja wymaga AJAX REQUEST
                (i === 1) && (submenu = true);

                // Tworzymy obiekt który uruchomi akcję
                runnables  = new marcheApp.type.Runnable(route[i],'#' + paths[i],runnables, paths[i]);
            }
            // Warunek sprawdza czy była akcja które wymaga AJAX REQUEST
            if ((paths.length >= 2 && submenu)|| (paths[0] && paths[0] === 'wydarzenia')){

                runnables = new marcheApp.type.Runnable(model,content,this.path.getPath(), this.generateView ,this.errorView , runnables);

                // Fix: Dodatkowy AJAX REQUEST dla wydarzeń
                if (paths[0] && paths[0] === 'wydarzenia' && loaded.length  === 0 && paths.length > 1) {
                    runnables = new marcheApp.type.Runnable(model,content,'/wydarzenia', this.generateView ,this.errorView , runnables);
                }
            }

            //Uruchomienie zgromadzonych akcji
            runnables && runnables.run();

            loaded = paths;

        }


})(marcheApp.event, marcheApp.model);

marcheApp.controller.generateView = function(callback, response){

   var res = $.parseJSON(response[0])

    if ('err' === res.stat) throw new Error(res.response);

   var address = $.address.pathNames();

   marcheApp.view.drawContent(res , callback);


};

marcheApp.controller.errorView = function(response){



};



