﻿
///
// Accordion (requires)
//  - jId: ID of element to be accordionized
//  - hierarchy of elements: jId > 'Item' > 'Text'
//  - min/max buttons to have class='AccordionToggle'
//  - * if there are multiple accordions on one page, it will treat as one accordion;
//      must use selector that returns multiple elements (e.g. class)
///
function Accordion(jId) {

    var self = this;
    this.id = jId;
    this.accordion;
    this.accordionItems;
    this.accordionItemsText;
    this.minImage;
    this.maxImage;

    this.Init = function() {
    	this.accordion = $(jId);
    	this.accordionItems = this.accordion.find('.Item').each(function() { $(this).css('visibility', 'hidden') });
    	this.accordionItemsText = this.accordion.find('.Item .Text');
    	this.minImage = Edentity.ResolveUrl('~/Images/Buttons/Toggle-Minus.png');
    	this.maxImage = Edentity.ResolveUrl('~/Images/Buttons/Toggle-Plus.png');

    	this.accordionItems.each(function() {
    		var title = $.trim($(this).find('.Title').text());
    		$(this).attr('name', TitleToFriendlyUrl(title));
    	});

    	$('img.AccordionToggle')
            .css('cursor', 'pointer')
            .attr('src', self.maxImage)
            .bind('click', function(e) {

            	var isOpen = $(this).attr('src').indexOf('Minus') > -1;
            	var text = $('.Text', $(this).parent().parent());  // find description field associated with +/-

            	if (isOpen) {
            		$(this).attr('src', self.maxImage);
            		if (text.length > 0) text.slideUp();
            	} else {
            		self.Collapse();
            		$(this).attr('src', self.minImage);
            		if (text.length > 0) text.slideDown('normal', function() {
            			self.SetHash($(this).parent().find('.Title').text());
            		});
            	}
            });

    	var hashPos = document.URL.indexOf('#', 0);

    	if (hashPos > 0) {
    		var friendlyUrl = document.URL.substr(hashPos + 1, document.URL.length - (hashPos + 1));
    		this.OpenItemUsingFriendlyTitle(friendlyUrl);
    	}

    	this.Show();
    }

    this.Collapse = function() {

        if (this.accordionItemsText.length <= 0) return;

        this.accordionItemsText.each(function() {
            if ($(this).is(":visible")) {
                $(this).slideUp();
                $('img', $(this).parent().parent()).attr('src', self.maxImage);
            }
        });
    }

    this.Show = function() {
        this.accordionItems.css('visibility', 'visible');
    }

    this.Stripe = function(cssClass) {
        this.accordion.each(function() {
            $('.Item:even', $(this)).addClass(cssClass);
        });
    }

    this.OnSelected = function(fn, img) {
    	this.accordionItems.each(function(n) {
    		$(this).find('.AccordionToggle').eq(0).bind('click', {item: $(this)}, fn);
    	});
    }

    this.EnableClickByTitle = function() {
    	this.accordion
    		.find('.Item .ItemBox .Title')
            .css('cursor', 'pointer')
            .bind('click', function(e) {
				
				var img = $(this).parent().find('.Right img');
            	var isOpen = img.attr('src').indexOf('Minus') > -1;
            	var text = $('.Text', $(this).parent());  // find description field associated with +/-

            	if (isOpen) {
            		img.attr('src', self.maxImage);
            		if (text.length > 0) text.slideUp();
            	} else {
            		self.Collapse();
            		img.attr('src', self.minImage);
            		if (text.length > 0) text.slideDown('normal', function() {
            			self.SetHash($(this).parent().find('.Title').text());
            		});
            	}
            });
    }

    this.OpenItemUsingFriendlyTitle = function(friendlyTitle) {
    	this.accordion
    		.find('.Item .ItemBox .Title')
			.each(function() {
				var url = TitleToFriendlyUrl($.trim($(this).text()));
				if (url == friendlyTitle) {
					var itemBox = $(this).parent();
					itemBox.find('.Right img').attr('src', self.minImage);
					itemBox.find('.Text').slideDown();
				}
			});
    }

    this.SetHash = function(text) {
    	if (text == undefined || text == null || text == '') {
    		window.location.hash = '#';
    	} else {
    		window.location.hash = '#' + TitleToFriendlyUrl($.trim(text));
    	}
    }

    this.Init();
}


///
// AddToFavourites (requires)
//  - jId: ID of element to be accordionized
//  - contentType: content type of object (e.g. Show, Confessions)
//  - contentID: ID of object
// (optional)
//  - addText: button text when item is not in favourites
//  - removeText: button text when item is in favourites
//
// Remarks:
//  - override "AddToFavoritesHover" CSS class to customize style on button hover
///
function AddToFavourites(jId, contentType, contentID, addText, removeText) {

    var self = this;
    this.id = jId;
    this.contentType = contentType;
    this.contentID = contentID;

    if (contentType == "Show") {
        this.addText = 'Add Show To Favourites';
        this.removeText = 'Remove From Favourites';
    }
    else if (contentType == "Blog") {
        this.addText = 'Add Blog To Favourites';
        this.removeText = 'Remove From Favourites';
    }

    if (addText != null && addText != '') this.addText = addText;
    if (removeText != null && removeText != '') this.removeText = removeText;
    
    this.asmxUrl;
    this.button;

    this.Init = function() {

    	this.button = $(jId);
    	this.asmxUrl = Edentity.ResolveUrl('~/WebServices/AjaxServices.asmx');

    	this.button.hover(function() {
    		$(this).addClass('AddToFavoritesHover');
    	}, function() {
    		$(this).removeClass('AddToFavoritesHover');
    	});

    	this.Check();

    	this.button.click(function(e) {
    		if ($(this).text() == self.addText) {
    			self.Add();
    		}
    		else {
    			self.Remove();
    		}
    	});
    }

    this.Add = function() {

    	var faveCookie = GetCosmoUserCookie();

    	if (faveCookie.length > 0) {
    		$.ajax({
    			type: "POST",
    			url: this.asmxUrl + '/AddToMyCosmo',
    			data: "{'ContentType':'" + this.contentType + "','ContentID':" + this.contentID + "}",
    			contentType: "application/json; charset=utf-8",
    			dataType: "json",
    			success: function(result) {
    				if (result.d != undefined && result.d != null) {
    					if (result.d == true) {
    						self.ChangeStatus(true);
    					}
    					else {
    						// console.log('Unable to add to favourites. Please check logs.');
    					}
    				}
    			}
    		});
    	}
    	else {
    		ShowLoginPopup(function() {
    			self.Add();
    		});
    	}
    }

    this.Remove = function() {

		var faveCookie = GetCosmoUserCookie();

		if (faveCookie.length > 0) {
    		$.ajax({
    			type: "POST",
    			url: this.asmxUrl + '/RemoveFromMyCosmo',
    			data: "{'ContentType':'" + this.contentType + "','ContentID':" + this.contentID + "}",
    			contentType: "application/json; charset=utf-8",
    			dataType: "json",
    			success: function(result) {
    				if (result.d != undefined && result.d != null) {
    					if (result.d == true) {
    						self.ChangeStatus(false);
    					}
    					else {
    						// console.log('Unable to remove from favourites. Please check logs.');
    					}
    				}
    			}
    		});
    	}
    	else {
    		ShowLoginPopup(function() {
    			self.Remove();
    		});
    	}
    }

    this.Check = function() {
    	
		$.ajax({
			type: "POST",
			url: this.asmxUrl + '/CheckMyCosmo',
			data: "{'ContentType':'" + this.contentType + "','ContentID':" + this.contentID + "}",
			contentType: "application/json; charset=utf-8",
			dataType: "json",
			success: function(result) {
				if (result.d != undefined && result.d != null) {
					self.ChangeStatus(result.d);
				}
			}
		});
	}

	this.ChangeStatus = function(isFave) {
		if (isFave == true) {
			this.button.text(this.removeText);
		}
		else {
			this.button.text(this.addText);
		}
	}

    this.Init();
}



///
// Rating (requires)
//  - rId: ID of rating element
//  - itemType: type of object
//  - itemID: id of object
// (optional)
//  - rated: rated element
///
function Rating(rId, itemType, itemId, rated) {

	var self = this;
	this.id = rId;
	this.itemType = itemType;
	this.itemId = itemId;
	this.rated = rated;
	this.onSubmittedCallback = function() { };

	this.Init = function() {
		$(this.id + ' .RatingStars').hide();
		$(this.id + ' .Thanks').hide();
	}

	this.GetRating = function() {

		$.ajax({
			type: "POST",
			url: baseUrl + 'WebServices/AjaxServices.asmx/RatingResults',
			data: "{'itemType':'" + this.itemType + "','itemID':" + this.itemId + "}",
			contentType: "application/json; charset=utf-8",
			dataType: "json",
			success: function(res) {

				if (res.d != undefined && res.d != null) {
					self.value = res.d;
					self.Render(self.value);
				}
			}
		});
	}

	this.Submit = function(value) {

		$.ajax({
			type: "POST",
			url: baseUrl + 'WebServices/AjaxServices.asmx/SubmitRating',
			data: "{'itemType':'" + this.itemType + "','itemID':" + this.itemId + ",'rating': " + value + ",'userID':null}",
			contentType: "application/json; charset=utf-8",
			dataType: "json",
			success: function(res) {

				if (res.d != undefined && res.d != null) {

					var rating = res.d;

					$(this.id + ' .RatingStars').hide();
					$(this.id + ' .Thanks').show();

					if (self.rated) {
						// TODO: **** NOT WORKING ****/
						// console.log('calling render rated');
						var x = eval(self.rated);
						x.Render(rating);
					}

					if (self.onSubmittedCallback) {
						self.onSubmittedCallback();
					}
				}
			}
		});

	}

	this.OnSubmitted = function(fn) {
		this.onSubmittedCallback = fn;
	}

	this.Render = function(n) {

		if (n <= 5 && n >= 0) {

			var rated = Math.ceil(n);
			var out = $("<div class='Left'></div>");

			for (var i = 1; i <= 5; i++) {
				var input = $("<input class='star2' type='radio' name='" + this.id + "' value='" + i + "' " + (i == rated ? "checked='checked'" : "") + " />");
				out.append(input);
			}

			$(this.id + ' .RatingStars').html(out).append('<div class="Clear" />').show();
			$(this.id + ' .RatingStars :radio.star2').rating({
				callback: function(value, link) {
					self.Submit(value);
				}
			});
		}
	}

	this.Init();
}



///
// Rated (requires)
//  - rId: ID of element to be rated
//  - itemType: type of object
//  - itemID: id of object
///
function Rated(rId, itemType, itemId) {

	var self = this;
	this.id = rId;
	this.itemType = itemType;
	this.itemId = itemId;
	this.value;

	this.Init = function() {
	
	}

	this.GetRating = function() {

		$.ajax({
			type: "POST",
			url: baseUrl + 'WebServices/AjaxServices.asmx/RatingResults',
			data: "{'itemType':'" + this.itemType + "','itemID':" + this.itemId + "}",
			contentType: "application/json; charset=utf-8",
			dataType: "json",
			success: function(res) {

				if (res.d != undefined && res.d != null) {
					self.value = res.d;
					self.Render(self.value);
				}
			}
		});
	}

	this.Render = function(n) {

		if (n <= 5 && n >= 0) {

			var rated = Math.ceil(n);
			var out = $("<div class='RatedStars'></div>");

			for (var i = 1; i <= 5; i++) {
				var input = $("<input class='star' type='radio' name='" + this.id + "' value='" + i + "' disabled='disabled' " + (i == rated ? "checked='checked'" : "") + " />");
				out.append(input);
			}

			$(this.id + ' .RatedStars').html(out);
			$(this.id + ' .RatedStars :radio.star').rating();
		}
	}

	this.CurrentValue = this.value;

	this.Init();
}