/**
 * Nutv application object
 * @module NutvApp
 */
var NutvApp = window.NutvApp || {};

/**
 * Creates module chain
 *
 * @namespace ADBSTB
 * @method  namespace
 * @param   {String} nsString Module chain string
 *
 * @return  {Object} medule itself
 */
NutvApp.namespace = function (nsString) {
    var parts = nsString.split('.'),
    parent = NutvApp,
    i,
    max;

    //strip one and only global - app name, if present
    if (parts[0] === parent.name) {
        parts = parts.slice(1);
    }

    max = parts.length;

    for (i = 0; i < max; i += 1) {
        if (typeof parent[parts[i]] === 'undefined') {
            parent[parts[i]] = {};
        }
        parent = parent[parts[i]];
    }
    return parent;
};
NutvApp.namespace('ui');
NutvApp.namespace('util');
NutvApp.namespace('cookie');
NutvApp.namespace('detect');

/**
 * Return unique id
 *
 * @namespace xsApp
 * @class util
 * @method uniqid
 * @param string prefix
 *
 * @return string
 */
NutvApp.util.uniqid = function (prefix) {
    var date = new Date();

    if (prefix === 'undefined') {
        prefix = '';
    }
    return prefix + '_' + Math.round(Math.random() * 10000) + '_' + date.getMilliseconds();
}

/**
 * @namespace xsApp.ui
 * @class iframeOverall
 */
NutvApp.ui.iframeOverall = {
    
    /**
     * @namespace xsApp.ui
     * @class iframeOverall
     * @method create
     * @param string url - link which whould be loaded whitin viewport
     * @param int width - please provide in px
     * @param int height - please provide in px
     * @return containerId
     */    
    create : function (url, width, height) {
        var tpl, containerId, createIframeContainer, container;

        /**
         * @namespace xsApp.ui
         * @class iframeOverall
         * @method createIframeContainer
         * @param string id - container id
         * @param string url - link which whould be loaded whitin viewport
         * @param int width - please provide in px
         * @param int height - please provide in px
         */
        createIframeContainer = function (containerId, url, width, height) {
            var tpl = '';
            tpl = tpl.concat("<div id='" + containerId + "' style='overflow:hidden;'>");
            tpl = tpl.concat("<iframe id='modalFrame' width='" + width + "' height='400' src='" + url + "' marginheight='0' marginwidth='0' frameborder='0' scrolling='no' scrollbar='no' scrolling='no' ALLOWTRANSPARENCY='true' style='overflow:hidden;overflow-x:hidden; overflow-y:hidden'></iframe>");
            tpl = tpl.concat("</div>");

            return tpl;
        };

        containerId = NutvApp.util.uniqid('iframe_overall');
        tpl = createIframeContainer(containerId, url, width, height);
        $('body').append(tpl);

        container = $("#" + containerId);
        container.dialog({
            modal: true,
            resizable: false,
            height : height,
            width : width,
            minHeight : height
        });
        container.parent('div.ui-dialog').find('div.ui-dialog-titlebar').remove();
        container.css('padding', 0);
        $('.ui-widget-overlay').css('opacity','0.85');
        
        //closing lightbox by clicking outside
        $('.ui-widget-overlay').click(function (e) {
            NutvApp.ui.iframeOverall.destroyAllOpenOverallDialogs();
        });   
        
        return containerId;
    },
    
    /**
     * @namespace xsApp.ui
     * @class iframeOverall
     * @method addIframeOverallInvocation
     * @param array modalWindowConf - must contain object(s) with properies ($element, url, width, height)
     * @throw Error if modalWindowConf is not an array
     */
    addIframeOverallInvocation : function (modalWindowConf) {
        var i, //used in loop
        conf,
        createOnClick;
        
        if (!$.isArray(modalWindowConf)) {
            throw new Error('Parameter passed to xsApp.ui.iframeOverall.addIframeOverallInvocation is not an array');
        }
    
        modalWindowConf = jQuery.grep(modalWindowConf, function(conf, i){
            return (conf.$element.length > 0); //remove configuration for not existed elements
        });

        /**
         * Return onClick event handler function 
         * @param object conf - must contain properies ($element, url, width, height)
         * 
         * @return function 
         */
        createOnClick = function (conf) {
            return function (e) {
                e.preventDefault();
                e.stopPropagation();
                NutvApp.ui.iframeOverall.create(conf.url, conf.width, conf.height);            
            }
        };

        for (i = 0; i < modalWindowConf.length; i++) {
            conf = modalWindowConf[i];
            conf.$element.click(createOnClick(conf));
        }
    },
    /**
     * @namespace xsApp.ui
     * @class iframeOverall
     * @method destroyAllOpenOverallDialogs
     * 
     * Close and destroy (remove html with iframe) opened dialog
     */
    destroyAllOpenOverallDialogs : function () {
        var $dialog = $('.ui-dialog-content'); //there should be only one dialog active
        $dialog.dialog("destroy");
        $dialog.remove();        
    }
};

/**
 * @namespace NutvApp
 * @class util
 * @method getQueryVariable
 * @param paramName - string
 * @param defaultValue - value returned if paramName is not set, defult is null
 * @return string param value
 * Get variable from url by name
 */
NutvApp.util.getQueryVariable = function (paramName, defaultValue) {
    var query = window.location.search.substring(1),
    vars = query.split("&"),
    pair,
    i;

    for (i = 0; i < vars.length; i++) {
        pair = vars[i].split("=");
        if (pair[0] === paramName) {
            return pair[1];
        }
    }
    return defaultValue || null;
};

/**
 * @namespace NutvApp
 * @class detect
 * @method isLoginButtonPresent
 * @return bool
 * Return true if login button is present on page
 */
NutvApp.detect.isLoginButtonPresent = function () {
    var loginButtonId = 'login-link';
    return ($('#' +loginButtonId).length > 0);
};

/**
 * @namespace NutvApp
 * @class cookie
 * @method isCookie
 * @param cookie name
 * @return bool
 */
NutvApp.cookie.isCookie = function (name) {
    var i, cookieName, cookieData, cookies=document.cookie.split(";");
    
    for (i = 0; i < cookies.length; i++)
    {
        cookieName = cookies[i].substr(0,cookies[i].indexOf("="));        
        cookieData = cookies[i].substr(cookies[i].indexOf("=")+1);
        cookieName = cookieName.replace(/^\s+|\s+$/g,"");
        if (cookieName === name) {
            return true;
        }
    }
    return false;
}

/**
 * @namespace NutvApp
 * @class cookie
 * @method deleteCookie
 * @param string name
 * @param string domain
 * @param string path
 * remember cookies not set by js cannot be removed by js
 */
NutvApp.cookie.deleteCookie = function (name, domain, path) {
    var cookie = name + '=;expires=0;' 
    if (undefined !== domain) {
        cookie = cookie + 'domain=' + domain + ';';
    }
    if (undefined !== path) {
        cookie = cookie + 'path=' + path + ';';
    }    
    document.cookie = cookie;
}

$(function () {
    var sessionCheckerInterval,
    modalWindowConf = [
    {
        $element : $('#login-link'),
        url : MM.config.shopLocation +'/user/auth',
        width : 1002,
        height : 400
    },
    {
        $element : $('#new-user-link'),
        url : MM.config.shopLocation +'/user/register',
        width : 1002,
        height : 450
    },
    {
        $element : $('#forgot-password-link'),
        url : MM.config.shopLocation +'/user/forgot-password',
        width : 1002,
        height : 450
    },
    {
        $element : $('#purchase-link'),
        url : MM.config.shopLocation + '/shop/productlist?media_id=' + $('#purchase-link').attr('data-media-id'),
        width: 1002,
        height: 450
    }];

    NutvApp.ui.iframeOverall.addIframeOverallInvocation(modalWindowConf);
    
    /**
     * Wait for signal for closing current dialog
     */
    pm.bind('close_dialog', function(data) {
        if ((data.logged === 1) && (NutvApp.detect.isLoginButtonPresent() === true)){
           window.location.href = window.location.href; 
        }
        NutvApp.ui.iframeOverall.destroyAllOpenOverallDialogs();
    });
    
    /**
     * Wait for signal to open register form 
     */    
    pm.bind('show_register_form', function(data) {
        var $registerLink = $('#new-user-link');
        NutvApp.ui.iframeOverall.destroyAllOpenOverallDialogs();
        if ($registerLink.length) {
            $registerLink.click();
        }
    });    
    
    /**
     * Wait for signal to open register form 
     */    
    pm.bind('show_reminder_form', function(data) {
        var $reminderLink = $('#forgot-password-link');
        NutvApp.ui.iframeOverall.destroyAllOpenOverallDialogs();
        if ($reminderLink.length) {
            $reminderLink.click();
        }
    });  
    

    /**
     * Wait for signal reload a page
     */    
    pm.bind('reload_page', function(data) {
        window.location.href = window.location.href;
    });
    /**
     * Wait for signal to redirect parent page 
     */    
    pm.bind('redirect_parent_page', function(data) {
        if (data.url) { 
            window.location.href = data.url;
        }
    });
    
    checkShopSession = function () {
        if (!NutvApp.cookie.isCookie('PHPSESSID')) {
            clearInterval(sessionCheckerInterval);
            NutvApp.cookie.deleteCookie(MM.config.userCoookieName, MM.config.userCoookieDomain, MM.config.userCoookiePath);
        }
    };
    sessionCheckerInterval = setInterval(checkShopSession, 1000);
    
    //fix for recurring payment
    if (MM.config.recurringPayment == 1) {
        var recurringContainerId = NutvApp.ui.iframeOverall.create(MM.config.shopLocation +'/shop/recurring-payment-remind', 1002, 450),
        container = $("#" + recurringContainerId);
        container.dialog('open');
    }
    
});

//gallery plugin
(function($) {
	$.fn.gallery = function(options) {
		var args = Array.prototype.slice.call(arguments);
		args.shift();
		this.each(function(){
			if(this.galControl && typeof options === 'string') {
				if(typeof this.galControl[options] === 'function') {
					this.galControl[options].apply(this.galControl, args);
				}
			} else {
				this.galControl = new Gallery(this, options);
			}
		});
		return this;
	};
	function Gallery(context, options) {this.init(context, options);};
	Gallery.prototype = {
		options:{},
		init: function (context, options){
			this.options = $.extend({
				duration: 700,
				slideElement:1,
				autoRotation: false,
				effect: false,
				listOfSlides: '.list > li',
				switcher: false,
				addClass:false,
				autoSwitcher: false,
				stopOnHover:false,
				disableBtn: false,
				nextBtn: 'a.link-next, a.btn-next, a.next',
				prevBtn: 'a.link-prev, a.btn-prev, a.prev',
				circle: true,
				clone: false,
				direction: false,
				event: 'click'
			}, options || {});
			var self = this;
			this.context = $(context);
			this.initEls();
			this.autoRotation = this.options.autoRotation;
			this.direction = this.options.direction;
			this.duration = this.options.duration;
			this.move = true;
			this.wrap = this.list.parent();
			if (this.options.nextBtn) this.nextBtn = this.context.find(this.options.nextBtn);
			if (this.options.prevBtn) this.prevBtn = this.context.find(this.options.prevBtn);

			this.calcParams(this);
			this.calcMinEls();
			
			if (this.options.autoSwitcher) {
				this.switcherHolder = this.context.find(this.options.switcher).empty();
				this.switchPattern = $('<ul class="'+ (this.options.autoSwitcher == true ? '' : this.options.autoSwitcher) +'"></ul>');
				for (var i=0;i<this.max+1;i++){
					$('<li><a href="#">'+i+'</a></li>').appendTo(this.switchPattern);
				}
				this.switchPattern.appendTo(this.switcherHolder);
				this.switcher = this.context.find(this.options.switcher).find('li');
				this.active = 0;
			} else {
				if (this.options.switcher) {
					this.switcher = this.context.find(this.options.switcher);
					this.active = this.switcher.index(this.switcher.filter('.active:eq(0)'));
				}
				else this.active = this.els.index(this.els.filter('.active:eq(0)'));
			}
			if (this.active < 0) this.active = 0;
			this.last = this.active;
			if (this.options.switcher) this.switcher.removeClass('active').eq(this.active).addClass('active');
			if (this.options.clone) this.active += this.count;
			
			if (this.options.effect) this.els.css({opacity: 0}).removeClass('active').eq(this.active).addClass('active').css({opacity: 1}).css('opacity', 'auto');
			else {
				if (this.direction) this.list.css({marginTop: -(this.mas[this.active])});
				else this.list.css({marginLeft: -(this.mas[this.active])});
			}
			
			if (this.options.nextBtn) this.initEvent(this, this.nextBtn,true);
			if (this.options.prevBtn) this.initEvent(this, this.prevBtn,false);
			if (this.options.addClass) this.els.removeClass('active').eq(this.active+1).addClass('active');
			
			this.initWindow(this,$(window));
			
			if (this.autoRotation) this.runTimer(this);
			
			if (this.options.switcher) this.initEventSwitcher(this, this.switcher);
			if (this.options.disableBtn && !this.options.circle && !this.options.clone) this.disableControls();
			
			if (this.options.stopOnHover) this.stopHover(this);
		},
		initEls: function(){
			this.els = this.context.find(this.options.listOfSlides);
			this.count = this.els.length;
			this.list = this.els.parent();
			if (this.options.clone) {
				this.list.append(this.els.clone());
				this.list.prepend(this.els.clone());
				this.els = this.context.find(this.options.listOfSlides);
			}
		},
		reCount: function(){
			this.initEls();
			this.calcParams(this);
			this.calcMinEls();
			if (this.options.effect) this.els.css({opacity: 0}).removeClass('active').eq(this.active).addClass('active').css({opacity: 1}).css('opacity', 'auto');
			else {
				if (this.direction) this.list.css({marginTop: -(this.mas[this.active])});
				else this.list.css({marginLeft: -(this.mas[this.active])});
			}
		},
		stopHover: function($this){
			this.context.bind('mouseenter', function(){
				$this.stop();
				$this.move = false;
			}).mouseleave(function(){
				$this.move = true;
				$this.play();
			});
		
		},
		calcMinEls: function(){
			if (this.sum <= (this.direction?this.wrap.outerHeight():this.wrap.outerWidth())) {
				if (this.options.nextBtn) this.nextBtn.css({visibility:'hidden'});
				if (this.options.prevBtn) this.prevBtn.css({visibility:'hidden'});
			}
		},
		calcParams: function(self){
			this.mas = [];
			this.sum = 0;
			this.max = this.count-1;
			this.width = 0;
			if (!this.options.effect) {
				this.els.each(function(){self.mas.push(self.width);self.width += self.direction?$(this).outerHeight(true):$(this).outerWidth(true);self.sum+=self.direction?$(this).outerHeight(true):$(this).outerWidth(true);});
				this.finish = this.direction?this.sum-this.wrap.outerHeight():this.sum-this.wrap.outerWidth();
				for (var i=0;i<this.count;i++){
					if (this.mas[i]>=this.finish) {
						this.max = i;
						break;
					}
				}
			}
		},
		changeSettings: function(set,val){
			this[set] = val;
		},
		fadeElement: function(){
			this.els.eq(this.last).animate({opacity:0}, {queue:false, duration: this.duration});
			this.els.removeClass('active').eq(this.active).addClass('active').animate({
				opacity:1
			}, {queue:false, duration: this.duration, complete: function(){
				$(this).css('opacity','auto');
			}});
			if (this.options.switcher) this.switcher.removeClass('active').eq(this.active).addClass('active');
			this.last = this.active;
		},
		scrollElement: function(f){
			if (this.direction) this.list.animate({marginTop: f ? -this.finish : -(this.mas[this.active])}, {queue:false, duration: this.duration});
			else this.list.animate({marginLeft: f ? -this.finish : -(this.mas[this.active])}, {queue:false, duration: this.duration});
			if (this.options.switcher) this.switcher.removeClass('active').eq(this.options.clone ? this.active < this.count ? this.active/this.options.slideElement : this.active >= this.count*2 ? (this.active - this.count*2)/this.options.slideElement : (this.active - this.count)/this.options.slideElement : this.active/this.options.slideElement).addClass('active');
			if (this.options.addClass) this.els.removeClass('active').eq(this.active+1).addClass('active');
		},
		runTimer: function($this){
			if($this._t) clearTimeout($this._t);
			if ($this.move) {
				$this._t = setInterval(function(){
					$this.nextStep();
				}, this.autoRotation);
			}
		},
		initEventSwitcher: function($this, el){
			el.bind($this.options.event, function(e){
				$this.active = $this.switcher.index($(this)) * $this.options.slideElement;
				if ($this.options.clone) $this.active += $this.count;
				$this.initMove();
				if ($this.autoRotation) $this.runTimer($this);
			});
		},
		initEvent: function($this, addEventEl, dir){
			addEventEl.bind($this.options.event, function(){
				if (dir) $this.nextStep();
				else $this.prevStep();
				if ($this.autoRotation) $this.runTimer($this);
				return false;
			});
		},
		disableControls: function(){
			this.prevBtn.removeClass(this.options.disableBtn);
			this.nextBtn.removeClass(this.options.disableBtn);
			if (this.active>=this.max) this.nextBtn.addClass(this.options.disableBtn);
			if (this.active<=0) this.prevBtn.addClass(this.options.disableBtn);
		},
		initMove: function(){
			var f = false;
			if (this.active >= this.max && !this.options.clone) {
				f = true;
				this.active = this.max;
			}
			if(this._t) clearTimeout(this._t);
			if (!this.options.effect) this.scrollElement(f);
			else this.fadeElement();
			if (this.options.disableBtn && !this.options.circle && !this.options.clone) this.disableControls();
		},
		nextStep:function(){
			var f = false;
			this.active = this.active + this.options.slideElement;
			if (this.options.disableBtn && !this.options.circle && !this.options.clone) this.disableControls();
			if (this.options.clone){
				if (this.active > this.count*2) {
					if (this.direction) this.list.css({marginTop:-this.mas[this.count]});
					else this.list.css({marginLeft:-this.mas[this.count]});
					this.active = this.count+this.options.slideElement;
				}
			} else {
				if (this.active >= this.max) {
					if (this.options.circle) {
						if (this.active > this.max) this.active = 0;
						else {
							this.active = this.max;
							f = true
						}
					}
					else {
						this.active = this.max;
						f = true;
					}
				}
			}
			if (!this.options.effect) this.scrollElement(f);
			else this.fadeElement();
		},
		prevStep: function(){
			var f = false;
			this.active = this.active - this.options.slideElement;
			if (this.options.disableBtn && !this.options.circle && !this.options.clone) this.disableControls();
			if (this.options.clone){
				if (this.active < 0) {
					if (this.direction) this.list.css({marginTop:-this.mas[this.count]});
					else this.list.css({marginLeft:-this.mas[this.count]});
					this.active = this.count-1;
				}
			} else {
				if (this.active < 0) {
					if (this.options.circle) {
						this.active = this.max;
						f = true;
					}
					else this.active = 0;
				}
			}
			if (!this.options.effect) this.scrollElement(f);
			else this.fadeElement();
		},
		initWindow: function($this,$window){
			$window.focus($.proxy(this.play,this));
			$window.blur($.proxy(this.stop,this));
		},
		stop: function(){
			if (this._t) clearTimeout(this._t);
		},
		play: function(){
			if (this.autoRotation) this.runTimer(this);
		}
	}
}(jQuery));
