﻿/// <reference path="jquery-1.4.1.min-vsdoc.js" />
$(document).ready(function () {
	/*Javascript for galleri */
	var currentImage = 0;
	$(".gallery-system p").hide();
	$(".gallery-system img").parent().show();

	if ($(".gallery-system").length) {
		$("table.event").remove();
		var text = "Photography by Hege Karoliussen";
		if ($(".xmas-event").length) {
			text = "Close";
		}

		$("body").append("<div class='hide gallery-viewer'><div class='imagearrowl'></div><div class='imagearrowr'></div><img src='' /><div class='gallery-content'><div class='text'></div></div><div class='close-viewer'>" + text + "</div></div>");
	}

	$(".image-s img").click(function () {
		$(".gallery-viewer img").attr("src", $(this).attr("alt"));

		var content = "";

		if ($(this).parent().hasClass("image-s")) {
			var parent = $(this).parent();
			content = parent.html();
			currentImage = parent.attr("class").split(" s")[1];
		}
		else {
			var parent = $(this).parent().parent();
			content = parent().html();
			currentImage = parent.attr("class").split(" s")[1];
		}
		$(".gallery-viewer .gallery-content .text").html(content).find("img, hr").remove();
		$(".gallery-viewer .gallery-content .text p").show();
		$(".fullscreen, .gallery-viewer").fadeIn(500);
	});
	$(".image-x img").click(function () {
		$(".gallery-viewer img").attr("src", $(this).attr("alt"));
		var content = "";

		if ($(this).parent().hasClass("image-x")) {
			var parent = $(this).parent();
			content = parent.html();
			currentImage = parent.attr("class").split(" x")[1];
		}
		else {
			var parent = $(this).parent().parent();
			content = parent().html();
			currentImage = parent.attr("class").split(" x")[1];
		}
		$(".gallery-viewer .gallery-content .text").html(content).find("img, hr").remove();
		$(".gallery-viewer .gallery-content .text p").show();
		$(".fullscreen, .gallery-viewer").fadeIn(500);
	});

	$(".gallery-viewer .close-viewer, .fullscreen").click(function () {
		$(".gallery-viewer, .fullscreen").hide();
	});
	$(".arrow-r-x-0").click(function () {
		$('.image-x').animate({
			left: '-=707'
		}, 2000, function () {
			// Animation complete.
		});

		$(".arrow-r-x-0").hide();
		$(".arrow-r-x-1").show();
		$(".arrow-l-x-1").show();
	});

	$(".arrow-r-x-1").click(function () {
		$('.image-x').animate({
			left: '-=707'
		}, 2000, function () {
			// Animation complete.
		});

		$(".arrow-l-x-2").show();
		$(".arrow-r-x-1").hide();
		$(".arrow-l-x-1").hide();
	});

	$(".arrow-l-x-1").click(function () {
		$('.image-x').animate({
			left: '+=707'
		}, 2000, function () {
			// Animation complete.
		});

		$(".arrow-r-x-0").show();
		$(".arrow-r-x-1").hide();
		$(".arrow-l-x-1").hide();
	});

	$(".arrow-l-x-2").click(function () {
		$('.image-x').animate({
			left: '+=707'
		}, 2000, function () {
			// Animation complete.
		});

		$(".arrow-l-x-2").hide();
		$(".arrow-r-x-1").show();
		$(".arrow-l-x-1").show();
	});

	$(".arrow-r").click(function () {
		$('.image-s').animate({
			left: '-=707'
		}, 2000, function () {
			// Animation complete.
		});

		$(".arrow-r").hide();
		$(".arrow-l").show();
	});
	$(".arrow-l").click(function () {
		$('.image-s').animate({
			left: '+=707'
		}, 2000, function () {
			// Animation complete.
		});

		$(".arrow-l").hide();
		$(".arrow-r").show();

	});

	$(".imagearrowl, .imagearrowr, .imagearrowl-x, .imagearrowr-x").hover(
          function () {
          	$(this).fadeTo(250, 0.75);
          },
          function () {
          	$(this).fadeTo(250, 0.0);
          }
        );

	$(".imagearrowr").click(function () {
		currentImage++;
		if ($(".xmas-event").length) {
			if (currentImage > 33)
				currentImage = 1;

			var content = $(".x" + currentImage).html();

			$(".gallery-viewer img").attr("src", $(".x" + currentImage).find("img").attr("alt"));
			$(".gallery-viewer .gallery-content .text").html(content).find("img, hr").remove();
			$(".gallery-viewer .gallery-content .text p").show();
		}
		else {
			if (currentImage > 11)
				currentImage = 0;

			var content = $(".s" + currentImage).html();
			$(".gallery-viewer img").attr("src", $(".s" + currentImage).find("img").attr("alt"));
			$(".gallery-viewer .gallery-content .text").html(content).find("img, hr").remove();
			$(".gallery-viewer .gallery-content .text p").show();
		}
	});

	$(".imagearrowl").click(function () {
		currentImage--;

		if ($(".xmas-event").length) {
			if (currentImage < 1)
				currentImage = 33;

			var content = $(".x" + currentImage).html();

			$(".gallery-viewer img").attr("src", $(".x" + currentImage).find("img").attr("alt"));
			$(".gallery-viewer .gallery-content .text").html(content).find("img, hr").remove();
			$(".gallery-viewer .gallery-content .text p").show();
		}
		else {
			if (currentImage < 0)
				currentImage = 11;

			var content = $(".s" + currentImage).html();

			$(".gallery-viewer img").attr("src", $(".s" + currentImage).find("img").attr("alt"));
			$(".gallery-viewer .gallery-content .text").html(content).find("img, hr").remove();
			$(".gallery-viewer .gallery-content .text p").show();
		}
	});
	/* added April 8 2010 */
	$("img.hover").hover(
      function () {
      	$(this).after("<img src='/css/images/rss-14x14.png' class='removeMe' />");
      	$(this).addClass('focused');
      },
      function () {
      	$('img.removeMe').remove();
      	$(this).removeClass('focused');
      }
    );
	/* addition ends */

	$('.js-clear').each(function () {
		$(this).attr("value2", $(this).attr("value"));
	});

	$('.js-clear').focus(function () {
		if ($(this).attr("value2") == $(this).attr("value")) {
			$(this).attr("value", "");
		}
	});

	$('.js-clear').blur(function () {
		if ("" == $(this).attr("value")) {
			$(this).attr("value", $(this).attr("value2"));
		}
	});

	$('.fullscreen').css("height", $(document).height());
	$('.fullscreen').css("width", $(document).width());

	// shows 300x300px img of product on product page
	$(".product .image img").hover(function () {
		$(".product .big").attr("src", $(this).attr("src2"));
		$(".product .big").attr("src2", $(this).attr("src3"));
	});

	// shows the popup on products on category page
	$(".relative-catch").hover(
      function () {
      	var p = $(this).position();
      	$(this).find(".popup").css("left", p.left - 21).css("top", p.top + 80).show();
      },
      function () {
      	$(this).find(".popup").hide();
      }
    );

	$('.profile-edit input.textbox').keyup(function (e) {
		if (e.which == 13 || e.keyCode == 13) {
			e.preventDefault();
			$(".profile-edit .update-button").click();
		}
	});

	// shows edit address on edit profile page
	$("input.edit-address").click(function (e) {
		$(this).parent().parent().hide().next().show();
	});

	// shows create address on edit profile page
	$("input.create-address").click(function (e) {
		$(this).hide().next().show();
	});

	// hides edit address on edit profile page
	$("div.edit-address input.button").click(function (e) {
		$(this).parent().parent().parent().parent().parent().hide().prev().show();
	});

	// hides/shows a group of products on category
	$(".toggle").click(function (e) {
		var isHidden = true;

		if ($(this).hasClass("minus"))
			isHidden = false;

		var obj = $(this).parent();
		while (obj.next().hasClass("relative-catch")) {
			obj = obj.next();

			if (isHidden)
				obj.show();
			else
				obj.hide();
		}

		$(this).find("img").attr("alt", "Show group");
		$(this).find("img").attr("title", "Show group");

		if (isHidden) {
			$(this).find("img").attr("src", "/css/images/minus.gif");
			$(this).removeClass("plus");
			$(this).addClass("minus");
		}
		else {
			$(this).find("img").attr("src", "/css/images/plus.gif");
			$(this).removeClass("minus");
			$(this).addClass("plus");
		}
	});

	// shows add wishlist edit fields on wishlist page
	$("a.add-wishlist").click(function (e) {
		$("table.add-wishlist").show();
	});

	// hides add wishlist edit fields on wishlist page
	$("table.add-wishlist input:button").click(function (e) {
		$("table.add-wishlist").hide();
	});

	// shows wishlists on product page
	$(".add-to-wishlist").click(function (e) {
		if ($("ul.wishlists").css('display') == 'none') {
			$("ul.wishlists").show();
		}
		else {
			$("ul.wishlists").hide();
		}
	});

	// hides wishlists on product page
	$("ul.wishlists").click(function (e) {
		$("ul.wishlists").hide();
	});

	// prints page
	$(".print").click(function () {
		window.print();
		return false;
	});

	// hides ie6 warning
	$(".ie6 .close").click(function () {
		$(this).parent().hide();
	});

	// mail a friend
	$(".mail-a-friend").click(function () {
		var content = $(".content .mail-a-friend-box").detach();
		if (content)
			$("form").append(content); // does this only once
		$(".mail-a-friend-box,.fullscreen").show();
	});

	$(".fullscreen").click(function () {
		$(".mail-a-friend-box").hide();
		$(".fullscreen").hide();
	});

	$(".participate .close, .fullscreen").click(function () {
		$(".fullscreen").hide();
		$(".participate").hide();
		$(".participate .inner").html("");
	});


	$(".submission").click(function () {

		$(".fullscreen").show();
		var link = $(this).attr("rel");
		var popupdiv = $(".participate .inner");
		popupdiv.load(link + " .detailswrapper", { action: "load" }, function (data) {

			$(".vote-button").click(function () {
				$.post(link, { action: "vote" }, function () {
					window.location = window.location;
				});
			});


			$(".participate .images .large img").hide();
			$(".participate .images .large img:first").show();

			$(".participate .images .small img").hover(function () {
				var thisclass = $(this).attr("class");
				$(".participate .images .large img").hide();
				$(".participate .images .large img." + thisclass).show();
			});
			$(".participate a.maillink").each(function () {
				var currentHref = $(this).attr("href");
				$(this).attr("href", function () {
					return decodeEmail(currentHref);
				});
				$(this).show();
			});
			$(".participate span.mailtext").each(function () {
				var currentText = $(this).text();
				var newText = decodeEmail(currentText);
				$(this).text(newText);
				$(this).show();
			});
			if ($(".translation").length) {
				$(".translation").each(function () {
					$(".translation ul li.languageselector").click(function () {

						var tab = $(this);
						$(".translation ul li").removeClass("selected");
						$(".translation div.lang").hide();
						var toShow = $(".translation div." + tab.find("img").first().attr("alt")).first();
						toShow.show();
						tab.addClass("selected");
						Submissions.Detail.tabSelected(tab, toShow);
					});
					$(".translation ul li.languageselector").first().click();
				});
			}
			$(".participate").show();
		});
		return false;
	});


	/* pre-sprint 11.02.10 changes ( and i change up on $(".submission").click ) */

	$("input.email-to-friend").click(function () {
		$(".fullscreen").show();
		$("div.email-to-friend").show();
	});

	$("div.email-to-friend .cancel").click(function () {
		$(".fullscreen").hide();
		$("div.email-to-friend").hide();
	});

	/* 24/03/10 changes */
	/* 25/03/10 changes */

	var pos = -200;
	$("#movingwindow img").each(function () {
		$(this).css("left", pos);
		pos += 100;
	});

	var infoid = "";
	$("#movingwindow .movingitem").hover(
      function () {
      	infoid = $(this).attr("infoid");
      	$("#movinginfo #movinginfo" + infoid).show();
      },
      function () {
      	$("#movinginfo #movinginfo" + infoid).hide();
      }
    );

	var pos = 0 - 200;
	$("#movingwindow img").each(function () {
		$(this).css("left", pos);
		pos += 100;
	});

	var infoid = "";
	$("#movingwindow .movingitem").hover(
      function () {
      	infoid = $(this).attr("infoid");
      	$("#movinginfo #movinginfo" + infoid).show();
      },
      function () {
      	$("#movinginfo #movinginfo" + infoid).hide();
      }
    );

	function slide() {
		var high = $("#movingwindow img:first");
		var low = $("#movingwindow img:first");

		$("#movingwindow img").each(function () {
			if ($(this).css("left") < low.css("left"))
				low = $(this);

			if ($(this).css("left") > high.css("left"))
				high = $(this);
		});

		var newLoc = high.css("left");
		newLoc = newLoc.substring(0, newLoc.length - 2);
		newLoc = newLoc - 0 + 100;

		low.css("left", newLoc + "px");
		$("#movingwindow").append($("#movingwindow img:first"));
		$("#movingwindow img").animate({
			left: '-=100'
		}, 2900, "linear", function () {
		});
	}

	var times = 0;
	$("#movingwindow").each(function () {
		$(document).everyTime(3000, function (i) {

			slide();

		}, times);
	});

	//Unobfuscate emails:
	$("a.maillink").each(function () {
		var currentHref = $(this).attr("href");
		$(this).attr("href", function () {
			return decodeEmail(currentHref);
		});
		$(this).show();
	});
	$("span.mailtext").each(function () {
		var currentText = $(this).text();
		var newText = decodeEmail(currentText);
		$(this).text(newText);
		$(this).show();
	});
});

function decodeEmail(encoded) {
	return encoded.replace(/[a-zA-Z]/g, function (c) { return String.fromCharCode((c <= "Z" ? 90 : 122) >= (c = c.charCodeAt(0) + 13) ? c : c - 26); });
}

function highlightError(doHighlight, widgetId) {
	if (doHighlight) {
		$(document).ready(function () {
			$('.' + widgetId).addClass('error');
		});
	}
}
function clearRadioGroup(groupName) {
	var selector = 'input[@name="' + groupName + '"]:checked';
	$(document).ready(function () {
		$(selector).attr('checked', false);
	});
}

var NewsletterTogglers = function (togglers, revealer, concealer) {
	this.togglers = togglers;
	this.revealer = revealer;
	this.concealer = concealer;
};

var NewsletterSelector = function (continents, continentNewsletters) {
	this.continents = continents;
	this.continentNewsletters = continentNewsletters;
};

NewsletterSelector.prototype.showAllNewsletters = function () {
	var self = this;
	self.continents.show();
	self.continentNewsletters.show()
        .children('li').each(function () {
        	$(this).show();
        	$(this).css("float", "left");
        });
};

NewsletterSelector.prototype.hideUnselectedNewsletters = function () {
	var self = this;
	self.continents.hide();
	self.continentNewsletters.hide()
        .children('li').each(function () {
        	if ($(this).hasClass("current") || $(this).find("input.checkbox").attr("checked")) {
        		$(this).show();
        		$(this).parent().show();
        	} else {
        		$(this).hide();
        	}
        	$(this).css("float", "none");
        });
};

NewsletterSelector.prototype.toggleNewsletter = function (chkSibling) {
	var chk = $(chkSibling).prevAll(':checkbox');
	chk.attr('checked', !chk.is(':checked'));
};

NewsletterSelector.prototype.attachClickListenersTo = function (chkSelectors, togglers) {
	var self = this;
	chkSelectors.click(function (sender) {
		self.toggleNewsletter(sender.target);
	});
	togglers.revealer.click(function (sender) {
		togglers.togglers.toggle();
		self.showAllNewsletters();
	});
	togglers.concealer.click(function (sender) {
		togglers.togglers.toggle();
		self.hideUnselectedNewsletters();
	});
};

NewsletterSelector.prototype.showNewsletterForSelectedCountry = function (sender, togglers) {
	var self = this;
	var selectedCountry = $(sender).find('option:selected').text().toLowerCase();
	self.showNewsletterFor(selectedCountry, togglers.revealer, togglers.concealer);
};

NewsletterSelector.prototype.attachChangeListernerTo = function (ddlCountries, togglers) {
	var self = this;
	ddlCountries.change(function (sender) {
		self.showNewsletterForSelectedCountry(sender.target, togglers);
	});
};


NewsletterSelector.prototype.tryMakeLocalCurrent = function (country) {
	var localFound = false;
	var self = this;
	self.continentNewsletters.children('li').removeClass("current").hide()
        .children("input.checkbox").attr("checked", false)
        .siblings('span').each(function () {
        	var newsletterCountry = $(this).html().toLowerCase();
        	if (country != "" && newsletterCountry.indexOf(country) > -1) {
        		//$(this).siblings(':checkbox').attr('checked', true);
        		$(this).parent().addClass("current").show();
        		localFound = true;
        	}
        });
	return localFound;
};

NewsletterSelector.prototype.makeGlobalCurrent = function () {
	var self = this;
	self.continentNewsletters.find('li span').each(function () {
		if ($(this).html().indexOf("Global") > -1) {
			//$(this).siblings(':checkbox').attr('checked', true);
			$(this).parent().addClass("current");
		}
	});
};

NewsletterSelector.prototype.showNewsletterFor = function (country, revealer, concealer) {
	var self = this;
	var localFound = self.tryMakeLocalCurrent(country);

	if (!localFound) {
		self.makeGlobalCurrent();
	}
	self.hideUnselectedNewsletters();
	$(revealer).show();
	$(concealer).hide();
};

NewsletterSelector.prototype.init = function (chkSelectors, togglers, ddlCountries) {
	var self = this;
	self.attachClickListenersTo(chkSelectors, togglers);
	self.attachChangeListernerTo(ddlCountries, togglers);
	self.hideUnselectedNewsletters(togglers.togglers);
	self.showNewsletterForSelectedCountry(ddlCountries, togglers);
};

var SharePostcard = SharePostcard || {};
SharePostcard.WhoReceived = {
	tabSelected: function (event, ui) {
		var tab = $(ui.panel);
		var lang = tab.data('lang');
		var errorMsg = tab.data('errormsg');
		if (lang) {
			var translated = tab.html();
			if (!translated.length) {
				var commentId = $(this).closest('.message').attr('data-commentid');
				var data = JSON.stringify({ postcardCommentId: commentId, targetLanguage: lang });
				
				$.ajax({
					type: 'POST',
					contentType: "application/json; charset=utf-8",
					url: '/services/GoogleTranslateService.svc/TranslatePostcard',
					data: data,
					dataType: "json",
					timeout: 3000,
					success: function (result) {
						tab.html(result.d);
					},
					error: function () {
						tab.html(errorMsg);
					}
				});
			}
		}
	}
};

var Submissions = Submissions || {};
Submissions.Detail = {
	tabSelected: function (tab, toShow) {
		var lang = tab.data('lang');
		var errorMsg = tab.data('errormsg');
		var alreadyTranslated = toShow.html();

		if (lang && !alreadyTranslated.length) {

			var submissionId = $(".translation").attr('data-submissionid');

			var data = JSON.stringify({ submissionId: submissionId, targetLanguage: lang });
			
			$.ajax({
				type: 'POST',
				contentType: "application/json; charset=utf-8",
				url: '/services/GoogleTranslateService.svc/TranslateSubmission',
				data: data,
				dataType: "json",
				timeout: 3000,
				success: function (result) {
					toShow.html(result.d);
				},
				error: function () {
					toShow.html(errorMsg);
				}
			});
		}
	}
};
