CreatoorSN.namespace('contributions');
CreatoorSN.contributions = {
	
	contributionTypes: [],
	gallery: null,
	getUrl: '/members/ajax/get-contributions/?',
	currentOrder: 'publishedDate',
	currentDirection: 'desc',
	currentType: 'all',
	currentCategory: 'all',
	currentId: null,
	contributionTabs: null,
	
	showAddContributionMenu : function(contributionTypes) {
		contributionTypes = YAHOO.lang.JSON.parse(contributionTypes);
		var addOptions = new YAHOO.widget.Menu('addContributionMenu', {position: 'static'});
		var submenu = [];
		for (var i = 0; i < contributionTypes.length; i++) {
			var element = {
				text: contributionTypes[i],
				id: contributionTypes[i] + '_id',
				url: '/edit/' + contributionTypes[i]
			};		
			submenu.push(element);
			CreatoorSN.contributions.contributionTypes.push(contributionTypes[i]);
		}
		var menuItems = [
            {
                text: 'dodaj',
                submenu: {
                    id: 'addOptions',
                    itemData: submenu
                }
            }
        ];
        addOptions.addItems(menuItems);
        addOptions.render('addContribution');
        addOptions.show();
	},
	
	setContributionTypes : function(contributionTypes) {
		CreatoorSN.contributions.contributionTypes = YAHOO.lang.JSON.parse(contributionTypes);
	},
	
	pagination : function (containerId, total, rowsPerPage, paginationContainers, url) {
		url = url ? url : CreatoorSN.contributions.getUrl;
		CreatoorSN.pagination.initialize(url, total, rowsPerPage, paginationContainers, containerId);
	},
	
	get : function(linkObj, containerId, paginationContainers, type, order, category) {
		if (type) {
			CreatoorSN.contributions.currentType = type;
		} else {
			type = CreatoorSN.contributions.currentType;
		}
		if (category) {
            CreatoorSN.contributions.currentCategory = category;            
        } else {
			category = CreatoorSN.contributions.currentCategory; 
		}
		var get = '';
		get += 'type=' + CreatoorSN.contributions.currentType;		
		order = order ? order : CreatoorSN.contributions.currentOrder;					
		if (order == CreatoorSN.contributions.currentOrder) {
			if (category == CreatoorSN.contributions.currentCategory && type == CreatoorSN.contributions.currentType) {
				if (CreatoorSN.contributions.currentDirection == 'desc') {
					CreatoorSN.contributions.currentDirection = 'asc';
				} else {
					CreatoorSN.contributions.currentDirection = 'desc';
				}
			}
		} else {
			CreatoorSN.contributions.currentDirection = order == 'publishedDate' || order == 'top-rated' ? 'desc' : 'asc';
			CreatoorSN.contributions.currentOrder = order;
		}
		get += '&order=' + CreatoorSN.contributions.currentOrder + '&dir=' + CreatoorSN.contributions.currentDirection;		
		get += '&category=' + CreatoorSN.contributions.currentCategory;
		recordsContainer = _$(containerId);
		if (!recordsContainer) {
			var redirect = '/';
			redirect += CreatoorSN.contributions.currentType == 'all' ? 'contributions' : CreatoorSN.contributions.currentType;
			redirect += '/' + CreatoorSN.contributions.currentCategory + '/' + CreatoorSN.contributions.currentOrder + '/' + CreatoorSN.contributions.currentDirection;
			location.replace(redirect);
			return false;
		} 
		recordsHTML = recordsContainer.innerHTML;
		recordsContainer.innerHTML = '<img src="/images/ajax-loader.gif" alt="loading" class="center" />';
		var url = CreatoorSN.contributions.getUrl + get;
		var oCallback = {                
            success : function (o) {
                var response = YAHOO.lang.JSON.parse(o.responseText);
                if (response.success) {
                    recordsContainer.innerHTML = response.html;
                    CreatoorSN.contributions.pagination(containerId, response.total, response.rowsPerPage, paginationContainers, url);
					var anchors = linkObj.parentNode.getElementsByTagName('a');
					for (var i = 0; i < anchors.length; i++) {
						anchors[i].className = '';						
					}
					linkObj.className = 'bold';
                } else {
                    recordsContainer.innerHTML = recordsHTML;
                    CreatoorSN.common.showErrorAlert(response.message);
                }
            },
            
            failure : function (o) {
                CreatoorSN.common.showErrorAlert(o.statusText);
            },
            timeout: CreatoorSN.common.iAjaxTimeout
        };
        YAHOO.util.Connect.asyncRequest(
            "GET",
            url,
            oCallback
        );
		return false;
	},
	
	showOpinionUsers : function (id, type, opinion) {
		var opinionCountDiv = _$('oc' + type + id);
		var url = "/default/ajax/get-contribution-opinion-users/";
		var get = "id=" + id + "&type=" + type + "&opinion=" + opinion;
		CreatoorSN.opinions.showUsers('opinionUsers' + type + id, opinionCountDiv, url, get, opinion);        
	},
	
	showRatingUsers : function (avgRating, id, type) {
		var url = '/default/ajax/get-contribution-rating-users/';
		var get = 'id=' + id + '&type=' + type;
		CreatoorSN.ratings.showUsers(type + 'RatingUsers' + id, avgRating, url, get);
	},
	//event, this, \'' . $id . '\', ' . $myRating .', ' . $this->_type . '
	rate : function (e, rateObj, id, startValue, type) {
		var callback = {
            fn: CreatoorSN.contributions.updateRating,
            params: {
                id: id,
				type: type
            }
        };
        CreatoorSN.ratings.rate(e, rateObj, callback, type + 'UserRating' + id, startValue);
	},
	
	updateRating : function (params) {
		var url = '/members/ajax/update-contribution-rating/';
        var get = 'id=' + params.id + '&rating=' + params.rating + '&starWidth=' + params.starWidth + '&type=' + params.type;
        var oCallback = {                
            success : function (o) {
				if (YAHOO.lang.JSON.isSafe(o.responseText)) {
					var response = YAHOO.lang.JSON.parse(o.responseText);
					if (response['success']) {
						var starsObj = _$(params.type + 'AvgRating' + params.id);
						if (starsObj) {
							starsObj.style.width = response.width + 'px';
							
							if (starsObj.parentNode.nextSibling) {
								starsObj.parentNode.nextSibling.innerHTML = response.rating + ' (<span>' + response.count + '</span>)';
							}
							starsObj.parentNode.onclick = function()
							{
								CreatoorSN.contributions.showRatingUsers(this, params.id, params.type);
							};
						}
						if (params.rateObj.parentNode.childNodes.length < 3) {
							var removeImg = new creaDomObject({
	                            tag: 'img',
	                            src: '/images/delete.gif',
	                            alt: CreatoorSN.common.translate('remove rating')
	                        });
	                        var removeRating = new creaDomObject({
	                            tag: 'a',
	                            href: '#',
	                            elements: [removeImg],
	                            wrapper : {
	                                tag: 'div',
	                                params: {
	                                    className: 'remove-rating left'
	                                }
	                            }
	                        });
							removeRating.domElement.onclick = function()
							{
								CreatoorSN.contributions.removeRating(this, params.id, params.type);
								return false;
							};
							removeRating.addTo(params.rateObj.parentNode);
						}
						params.stars.enable();
					} else {
						if (response.noAuth) {
							var login = new noAuth(function (noAuthObj){
								CreatoorSN.contributions.updateRating(params);
							}, response.message);
							return;
						}
						params.stars.enable();
						CreatoorSN.common.showErrorAlert(response.message);
						params.stars.curStar.style.width = response['width'] + 'px';
						if (params.stars.curUser) {
							params.stars.curUser.innerHTML = response['rating'];
						}
					}
				} else {
					params.stars.enable();
					CreatoorSN.common.showErrorAlert(CreatoorSN.common.translate('neznana napaka'));
				}
            },
            
            failure : function (o) {
                params.stars.enable();
                CreatoorSN.common.showErrorAlert(o.statusText);
            },
            timeout: CreatoorSN.common.iAjaxTimeout
            
        };
        YAHOO.util.Connect.asyncRequest(
            "POST",
            url,
            oCallback,
            get
        );
	},
	
	removeRating : function(obj, id, type) {
		obj.onclick = function() {return false;};
        var rateObj = obj.parentNode.parentNode.firstChild;
        var stObj = new stars(
            {
                rateObj: rateObj,
                startValue: 0,
                starWidth: CreatoorSN.common.starWidth
            }
        );
        stObj.disable();
        var avgObject = _$(type + 'AvgRating' + id);
        var oCallback = {
            success: function(o) {
                if (YAHOO.lang.JSON.isSafe(o.responseText)) {
                    var response = YAHOO.lang.JSON.parse(o.responseText);
                    if (response.success) {
                        obj.parentNode.parentNode.removeChild(obj.parentNode);
                        stObj.enable();
                        CreatoorSN.ratings.rateObject = CreatoorSN.ratings.starsObject = null;
                        rateObj.firstChild.style.width = '0px';
                        rateObj.nextSibling.innerHTML = 0;
                        rateObj.onmousemove = function(e)
                        {
                            CreatoorSN.contributions.rate(e, this, id, 0, type);
                        };
                        var width = Math.round(parseFloat(response['rating'] * CreatoorSN.common.starWidth));
                        avgObject.style.width = width + 'px';
                        if (avgObject.parentNode.nextSibling) {
                            avgObject.parentNode.nextSibling.innerHTML = response['rating'] + ' (<span>' + response['count'] + '</span>)';
                        }
                        avgObject.parentNode.onclick = parseInt(response['count']) ? function() {CreatoorSN.contributions.showRatingUsers(avgObject, id, type);} : function(){return false;};
                    } else {
						if (response.noAuth) {
							var login = new noAuth(function(noAuthObj){
								CreatoorSN.contributions.removeRating(obj, id, type);
							}, response.message, function(){stObj.enable();});
							return;
						}
                        stObj.enable();
                        CreatoorSN.common.showErrorAlert(response.message);
                    }
                } else {
                    stObj.enable();
                    CreatoorSN.common.showErrorAlert(CreatoorSN.common.translate('neznana napaka'));
                }
            },
            failure: function(o) {
                stObj.enable();
                CreatoorSN.common.showErrorAlert(o.statusText);
            },
            timeout: CreatoorSN.common.iAjaxTimeout
        };
		
        YAHOO.util.Connect.asyncRequest(
            "POST",
            '/members/ajax/remove-contribution-rating',
            oCallback,
            'id=' + id + '&type=' + type
        );
    
	},
    
    /**
     * Ajax Request to add current contribution to users favourites
     *
     * @param {Object} rateObj
     * @param {String} id
     * @param {String} type
     * @return void
     */
	addToFavourites : function (rateObj, id, type) {
        
        var oCallback = {
            
            success : function (o) {
                
                if (YAHOO.lang.JSON.isSafe(o.responseText)) {
                    
                    var response = YAHOO.lang.JSON.parse(o.responseText);
					if (response.success) {
                        CreatoorSN.common.showNote(response.message, rateObj, 'recipes', 'favourite');                       
					} else {					   
						if (response.noAuth) {
							var login = new noAuth(function (noAuthObj) {
								CreatoorSN.contributions.addToFavourites(rateObj, id, type);
							}, response.message);
							return;
						}
						CreatoorSN.common.showErrorAlert(response.message);                        
					}
					                
                }
                
            },
            
            failure : function (o) {
                CreatoorSN.common.showErrorAlert(o.statusText);
            },
            
            timeout: CreatoorSN.common.iAjaxTimeout
            
        };

        YAHOO.util.Connect.asyncRequest(
            "POST",
            '/members/ajax/add-contribution-to-favourites',
            oCallback,
            'type=' + type + '&token=' + id
        );

	},
    /**
     * Ajax Request to add current contribution to users favourites
     *
     * @param {Object} rateObj
     * @param {String} id
     * @param {String} type
     * @return void
     */
    addToRecommendations : function (rateObj, id, type) {
        
        var oCallback = {
            
            success : function (o) {
                
                if (YAHOO.lang.JSON.isSafe(o.responseText)) {
                    
                    var response = YAHOO.lang.JSON.parse(o.responseText);
                    if (response.success) {
                        CreatoorSN.common.showNote(response.message, rateObj, 'recipes', 'recommendation');                       
                    } else {                       
                        if (response.noAuth) {
                            var login = new noAuth(function (noAuthObj) {
                                CreatoorSN.contributions.addToFavourites(rateObj, id, type);
                            }, response.message);
                            return;
                        }
                        CreatoorSN.common.showErrorAlert(response.message);                        
                    }
                                    
                }
                
            },
            
            failure : function (o) {
                CreatoorSN.common.showErrorAlert(o.statusText);
            },
            
            timeout: CreatoorSN.common.iAjaxTimeout
            
        };

        YAHOO.util.Connect.asyncRequest(
            "POST",
            '/members/ajax/add-contribution-to-recommendations',
            oCallback,
            'type=' + type + '&token=' + id
        );

    },
	
	startPageTabs : function (type, containerId, active, get) {
		
		get = get ? '?' + get : '';
		var latest = {
			cacheData: true,
			label: CreatoorSN.common.translate('Latest')
		};
		var topRated = {
			cacheData: true,
            label: CreatoorSN.common.translate('Top rated')
		};
		var mostViewed = {
			cacheData: true,
            label: CreatoorSN.common.translate('Most viewed')
		};
		latest.active = active == 'latest';
		topRated.active = active == 'topRated';
		mostViewed.active = active == 'mostViewed';
		switch (type) {
			case 'recipes':
			    latest.dataSrc = '/default/ajax/latest-recipes-list/' + get;
				topRated.dataSrc = '/default/ajax/top-rated-recipes-list/' + get;
				mostViewed.dataSrc = '/default/ajax/most-viewed-recipes-list/' + get;				
			break;
			default:
			break;
		}
		var tabView = new YAHOO.widget.TabView();
         
        var latestTab = new YAHOO.widget.Tab(latest);
		var topRatedTab = new YAHOO.widget.Tab(topRated);
		var mostViewedTab = new YAHOO.widget.Tab(mostViewed);
		tabView.addTab(latestTab);
		tabView.addTab(topRatedTab);
		tabView.addTab(mostViewedTab);
		tabView.appendTo(containerId);
	},
	
	getSearchCriteria : function (form) {
		
		for (var i = 0; i < form.elements.length; i++) {
			//console.log(form.elements[i].name);
		}
	},
	
	toggleAdvancedSearch : function () {
		
	},
	
	buildMenu: function (menuCategories, containerId, type, keyword, member, group, order) {
		
		if (YAHOO.lang.JSON.isSafe(menuCategories)) {
		    
			var categories = YAHOO.lang.JSON.parse(menuCategories);
			//console.log(categories);
			if (YAHOO.lang.JSON.isSafe(keyword)) {
				keyword = YAHOO.lang.JSON.parse(keyword);
			}
			//console.log(keyword);
			var menu = new YAHOO.widget.Menu(containerId, {
				position: 'static',
				hidedelay: 750,
				lazyload: true,
				shadow: false
			});
			var submenus = [];
			for (var i = 0; i <  categories.length ; i++) {
				submenus[i] = {
					id: categories[i].urlIdentifier,
					itemdata: []
				};
				var _keyword = is_array(keyword) ? keyword[i] : keyword;
				CreatoorSN.contributions.buildSubmenus(submenus[i], categories[i].children, type, _keyword, member, group, order);
			}
			menu.subscribe('beforeRender', function (){
				
				if (this.getRoot() == this) {
					for (var i = 0; i < submenus.length; i++) {
						if (submenus[i].itemdata.length) {
							this.getItem(i).cfg.setProperty('submenu', submenus[i]);
						}
					}
				}
			});
			/*menu.subscribe('click', function () {
				console.log(this);
				var sm = menu.getSubmenus();
				for (var i = 0; i < sm.length; i++) {
					sm[i].hide();
				}
			});*/
			menu.render();	
		}
	},
	
	buildSubmenus: function (submenus, children, type, keyword, member, group, order)
	{
		if (children && children.length) {
			
			for(var i = 0; i < children.length; i++) {
				var url = '/' + type + '/browse/' + keyword + '/' + children[i].urlIdentifier;
				if (member) {
					url += '/member/' + member;
				}
				if (group) {
					url += '/group/' + group;
				}
				if (order) {
					url += '/order/' + encodeURIComponent(order);
				}
				var item = {
					text: children[i].categoryName,
					url: url
				};
				
				if (children[i].children && children[i].children.length) {
					item.submenu = {
					   id: children[i].urlIdentifier,
					   itemdata: []
					};
					CreatoorSN.contributions.buildSubmenus(item.submenu, children[i].children, type, keyword, member, group, order);
				}
		        submenus.itemdata.push(item);
				
			}
			
		}
	},
	
	hideSubcategories: function(listId, linkEl)
	{
		var list = _$(listId);
		var initialHeight = list.clientHeight;
        list.style.overflow = 'hidden';
		var animationUp = new YAHOO.util.Anim(listId, {
            height: {to: 0}
        }, 1, YAHOO.util.Easing.easeOut);
        var animationDown = new YAHOO.util.Anim(listId, {
            height: {to: initialHeight}
        }, 1, YAHOO.util.Easing.easeOut);
        animationUp.onComplete.subscribe(function() {
            list.style.visibility = 'hidden';
			linkEl.innerHTML = CreatoorSN.common.translate('show');
			linkEl.style.backgroundImage = 'url(/images/show.png)';
            linkEl.onclick = function() {                
				list.style.visibility = 'visible';
                list.style.overflow = 'hidden';
                animationDown.animate();
				return false;
            };
        });
        animationDown.onComplete.subscribe(function() {
            list.style.overflow = 'auto';
			linkEl.innerHTML = CreatoorSN.common.translate('hide');
			linkEl.style.backgroundImage = 'url(/images/hide.png)';
            linkEl.onclick = function() {                
				list.style.overflow = 'hidden';
                animationUp.animate();
				return false;
            };
        });
        animationUp.animate();
	},
	
	initTabs: function (elementId) {
		CreatoorSN.contributions.contributionTabs = new YAHOO.widget.TabView(elementId);
	},
	
	setSelectedTab: function () {
		
		if (CreatoorSN.contributions.contributionTabs) {
			var hash = location.hash;
			if (hash) {
				var index = 0;
				hash = hash.replace('#contribution', '');
				var contents = _$('contributionContents');
				for (var i = 0; i < contents.childNodes.length; i++) {
					if (contents.childNodes[i].id == hash) {
						index = i;
						break;
					}
				}
				CreatoorSN.contributions.contributionTabs.selectTab(index);
			}
		}
	},
	openFloatVideoList: function (videos){
		//
		//alert(photos);
		var scrPos = getScrollPosition();
		var videoGalleryContainer = new creaDomObject(
				{
					tag: 'div',
					id:'contribution-video-gallery',
					className: 'contribution-videos',
					wrapper: {tag: 'div'}

				}
			);
		var cancelButton = new creaDomObject(
				{
					tag: 'div',
					id:'cancelBotton',
					className: 'submitBotton right',
					html: CreatoorSN.common.translate('Close'),
					style:{cssCursor:'pointer',cssCursor:'hand'}
												 
				}
			);	
		cancelButton.domElement.onclick = function(){
			videoGalleryBox.close();
				return false;
			};
		var baseWidth = videos.length > 1 ? 700 : 500;	
		videoGalleryBox = new creaDomWindow(
			    {
			    	modal:true,
					header: {title: CreatoorSN.common.translate('Attached videos')},
					width: (baseWidth + 10),
					content: {elements: [videoGalleryContainer,cancelButton]},
                    position: {
                        top: (scrPos.y + 50),
                        left: 'none'
                    }

				}
			);
			
		videoGalleryBox.open();
		CreatoorSN.videos.showPlayerAndPlaylist('contribution-video-gallery', 'videoGalleryPlayer', videos, baseWidth);
	},
	openFloatGalery: function (photos){
		//
		//alert(photos);
		var scrPos = getScrollPosition();
		var galleryContainer = new creaDomObject(
				{
					tag: 'div',
					id:'contribution-gallery',
					className: 'contribution-gallery'
					

				}
			);
		var cancelButton = new creaDomObject(
				{
					tag: 'div',
					id:'cancelBotton',
					className: 'submitBotton right',
					html: CreatoorSN.common.translate('Close'),
					style:{cssCursor:'pointer',cssCursor:'hand'}
												 
				}
			);	
		cancelButton.domElement.onclick = function(){
				galleryBox.close();
				return false;
			};
			
		galleryBox = new creaDomWindow(
			    {
			    	modal:true,
					header: {title: CreatoorSN.common.translate('Attached photos')},
					content: {elements: [galleryContainer,cancelButton]},
					position: {
						top: (scrPos.y + 50),
						left: 'none'
					},
					width: 560

				}
			);
			
			galleryBox.open();
			YAHOO.util.Event.onDOMReady(function() {
				var  gallery  = new CSNcarousel({targetElId: 'contribution-gallery', photoArray: photos});
			});
	}
	
};
YAHOO.util.Event.onDOMReady(function() {
	if (location.hash) {
		var link = null;
		switch (location.hash) {
			case '#gallery':
				link = _$('contributionGallery');
			break;
			case '#videos':
				link = _$('contributionVideos');
			break;
		}
		if (link) {
			link.onclick();
		}
	}
});

