var $j = jQuery.noConflict(),
	clsd = {},
	vrnts = [],
	vrntDflt = "",
	vrnt;

$j(document).ready(function() {
	clsd = {
		popup : function(type) {
			var $popper = $j("#popinfo"),
				content,
				popwide;
			switch (type) {
				case "size" :
					content = "<img src='/images/info/" + type + ".png' />";
				break;
				case "care" :
					content = "<img src='/images/info/" + type + ".png' />";
				break;
				case "stylewomen" :
					content = "<img src='/images/info/styles-women.png' />";
				break;
				case "stylemen" :
					content = "<img src='/images/info/styles-men.png' />";
				break;
				case "shipping" :
					content = "<iframe src='/shipping' width='500' height='450' frameborder='0'></iframe>";
				break;
				case "glossary" :
					content = "<iframe src='/glossary' width='500' height='450' frameborder='0'></iframe>";
				break;
			}
			window.scroll(0,0);
			$popper.html(content);
			if (type === "shipping" || type === "glossary") {
				popwide = $popper.width();
				$popper
					.css("margin-left", "-250px")
					.show();
			} else {
				$j(content).load(function() {
					popwide = $popper.width();
					$popper
						.css("margin-left", "-" + (popwide/2) + "px")
						.show();
				});
			}
		},
		fbshare : function(x, text, image, title) {
			if (image) {
				FB.ui({
					method: 'stream.publish',
					message: '"' + text + '" - ' + x,
					attachment: {
						name: title,
						href: 'http://www.closed.com',
						media: [{
							type : 'image',
							src: image,
							href: image
						}]
					},
					user_message_prompt: 'Share with Facebook'
				}, function(response) {
					if (response && response.post_id) {
						//alert('Your comment was published to your wall.');

					} else {
						//alert("not pulished");

					}
				});
			} else {
				FB.ui({
					method: 'stream.publish',
					message: '"' + text + '" - ' + x,
					attachment: {
						name: x + ' x The X x Closed',
						href: 'http://www.closed.com'
					},
					user_message_prompt: 'Share with Facebook'
				}, function(response) {
					if (response && response.post_id) {
						//alert('Your comment was published to your wall.');

					} else {
						//alert("not pulished");

					}
				});
			}
		},
		shophome : function() {
			var $slds = $j("#slides"),
				tsft = 0,
				sft = 790;
			setInterval(function() {
				$slds.animate({
					"left": "-=" + sft + "px"
				}, 2000, function() {
					sft = sft + 1;
					tsft = tsft + sft;
					if (tsft >= 3164) {
						setTimeout(function() {
							$slds
								.css("position","relative")
								.css("left", "0");
							sft = 790;
							tsft = 0;
						}, 2800);
					}
				});
			}, 7000);
		},
		variants : function() {
			//console.log(vrnts);
			var clrBox = $j("#clsdColorVariant"),
				sizBox = $j("#clsdSizeVariant").children("select"),
				slpt,
				vrntsLng = vrnts.length,
				slctClr,
				slctSiz,
				slctFnl,
				lnk,
				opts = {};
			this.clrs = [];
			this.sizs = [];
			for (var i = 0; i < vrntsLng; i++) {
				slpt = vrnts[i].item.split("|");
				slpt[0] = slpt[0].split(' ').join('_');
				if (!clrBox.children("div").is("#" + slpt[0] + "")) {
					clrBox.append("<div id='" + slpt[0] + "' class='vrntColor'><img src='" + vrnts[i].swatch + "' /></div>");
					opts[slpt[0]] = [slpt[1]];
				} else {
					opts[slpt[0]].push(slpt[1]);
				}
			}
			function loadSizs(clr, dflt) {
				if (!$j("#clsdSizeVariant").is(":visible")) {
					$j("#clsdSizeVariant").fadeIn("slow");
				}
				clr = opts[clr];
				clr.sort(function(a,b){return a - b});
				sizBox.empty();
				for (var i = 0; i < clr.length; i++) {
					sizBox.append("<option id='" + clr[i] + "' value='" + clr[i] + "' class='vrntSize'>" + clr[i] + "</option>");
				}
				sizBox.children("#" + vrntDflt[1] + "").attr("selected", "selected");
				if (dflt) {
					slctClr = vrntDflt[0];
					slctSiz = vrntDflt[1];
				}
				var allSize = $j(".vrntSize");
					frstSize = allSize[0].id;
				if (frstSize !== vrntDflt[1]) {
					//console.log("frst = " + frstSize + " / default = " + vrntDflt[1]);
					for (i in allSize) {
						if (!sizBox.children("option").is("#" + vrntDflt[1] + "")) {
							sizBox.prepend("<option id='" + vrntDflt[1] + "' value='" + vrntDflt[1] + "' class='vrntSize'>" + vrntDflt[1] + "</option>");
						}	
					}
					sizBox.children("#" + vrntDflt[1] + "").attr("selected", "selected");
					slctSiz = vrntDflt[1];
				}
			}
			vrntDflt = vrntDflt.split("|");
			vrntDflt[0] = vrntDflt[0].split(' ').join('_');
			clrBox.children("#" + vrntDflt[0] + "").css("border", "2px solid #d7d7d7");
			loadSizs(vrntDflt[0], "yes");
			//
			function goToSelection() {
				slctClr = slctClr.split('_').join(' ');
				scltFnl = slctClr + "|" + slctSiz;
				//console.log(scltFnl);
				for (var j = 0; j < vrntsLng; j++) {
					if (scltFnl === vrnts[j].item) {
						lnk = vrnts[j].prdhref;
						break;
					}
				}
				//console.log(lnk);
				window.location.href = lnk;
			}
			clrBox.children("div").bind("click", function() {
				slctClr = this.id;
				//console.log(slctClr);
				$j(".vrntColor").css("border", "2px solid #fff");
				$j(this).css("border", "2px solid #d7d7d7");
				loadSizs(slctClr);
			});
			sizBox.bind("change", function() {
				slctSiz = $j("#clsdSizeVariant > select > option:selected");
				slctSiz = slctSiz[0].id;
				goToSelection();
			});
		},
		shopcatnav : function() {
			var $n = $j("#shopLeftNav"),
				ntop = 0,
				nst;
			if ($n.offset()) {
				ntop = $n.offset().top;
				nst = $n.css("position");
				$j(window).scroll(function() {
					var s = $j(this).scrollTop();
				
					if (s >= ntop) {
						$n.css({
							"position" : "fixed",
							"top" : "0px"
						});
					} else {
						$n.css("position", "" + nst + "");
					}
				});
				$j(".shopLang").accordion({
					active: false,
					event: 'click',
					autoHeight: false,
					animated: 'easeslide',
					collapsible: true
				});
			}
		},
		storesearch : function() {
			var $countrySelect = $j("#storeCountrySearch"),
				$citySelect = $j("#storeCitySearch");
			//
			$j.expr[':'].icontains = function(obj, index, meta, stack){
				return (obj.textContent || obj.innerText || jQuery(obj).text() || '').toLowerCase().indexOf(meta[3].toLowerCase()) >= 0;
			};
			//
			$j("#locator").fadeIn();
			function search(s) {
				var stat = $j("#results > p"),
					r,
					rlng,
					rtxt;
				if ($j(".store:icontains('" + s + "')")) {
					r = $j(".store:icontains('" + s + "')");
					rlng = r.length;
					$j(".store, .allstore").hide();
					r.show().parent().show();
					(r.length > 1) ? rtxt = "You have " + rlng + " results." : rtxt = "You have 1 result.";
					stat.text(rtxt);
					setTimeout(function() {
						stat.text("");
					},5000);
				} else {
					stat.text("No match.");
					setTimeout(function() {
						stat.text("");
					},5000);
				}
			}
			for (i in allCats) {
				if (allCats[i].parent === "4") $countrySelect.append("<option value='" + allCats[i].cat_ID + "'>" + allCats[i].cat_name + "</option>");
			}
			$citySelect.bind("change", function() {
				var s = $j(this).val();
				search(s);
			});
			$countrySelect.bind("change", function() {
				var s = $j(this).val();
				$citySelect
					.empty()
					.append("<option value='' selected>Select a City</option>")
					.show();
				for (i in allCats) {
					if (allCats[i].parent === s) $citySelect.append("<option value='" + allCats[i].name + "'>" + allCats[i].cat_name + "</option>");
				}
			});
			$j("#submitStoreSearch").bind("click", function() {
				var s = $j("#storeSearch").val();
				search(s);
			});
		},
		dropmenu : function() {
			$j("ul.dropdown li").hover(
				function() {
					$j(this).addClass("hover");
					$j('ul:first',this).css('visibility', 'visible');
				},
				function() {
					$j(this).removeClass("hover");
					$j('ul:first',this).css('visibility', 'hidden');
				}
			);
			// $j("ul.dropdown li ul li:has(ul)")
			// 				.find("a:first")
			// 				.append(" &raquo; ");
		},
		homemovie : function() {
			var params = {
				allowScriptAccess: "always",
				allowfullscreen : "true",
				wmode : "transparent"
			},
			atts = {
				id: "x-player"
			};
			swfobject.embedSWF(
				//"http://www.youtube.com/apiplayer?enablejsapi=1&version=3&playerapiid=ytplayer",
				"http://www.youtube.com/v/HtXVJVygQ7M?enablejsapi=1&version=3&autoplay=1&color1=0xb1b1b1&color2=0xcfcfcf&fs=1&playerapiid=ytplayer",
				"x-player",
				"790",
				"444",
				"9.0.0",
				null,
				null,
				params,
				atts
			);
		},
		homefeed : function() {
			var flashvars = {
				key : "ABQIAAAAIOtEYP2gnT7BBY5LOi6AsxRjVPlphFjN6pMU1ykndmLitihF1hTML1PPiXdygos-ez0Q78Y6g0vsYQ",
				feedUrl : "/feeds/allfeed_get.php"
			};
			var params = {
				menu : "false",
				scale : "noscale",
				wmode : "transparent"
			};
			var attributes = {};
			swfobject.embedSWF("/flash/home.swf", "hp-feed", "960", "655", "9.0.0", "expressInstall.swf", flashvars, params, attributes);
			/*
			$j("#hp-feed").load(function() {
				$j("#about-text").fadeOut("slow");
			});
			if($j("#hp-feed").complete) $j("#hp-feed").trigger("load");
			*/
			$j("#about-text").fadeOut("slow");
		},
		events : function() {
			$j("#hp-view-feed").click(function() {
				$j("#homepage")
					.animate({
						height : "654px"
					}, 800, function() {
						clsd.homefeed();
						$j(this).css("background-image", "none");
					});
			});
			$j("#hp-view-film").click(function() {
				$j("body").append("<div id='x-film'><div id='x-player'></div></div>");
				$j("#x-film").fadeIn();
				clsd.homemovie();
			});
			$j("#x-film").live("click", function() {
				$j(this).hide();
			});
			$j("#shopModule").click(function() {
				document.location.href = "http://www.closed.com/shop";
			});
			$j(".facebook").bind("click", function() {
				window.open("http://www.facebook.com/closed", "social-window");
			});
			$j(".twitter").bind("click", function() {
				window.open("https://twitter.com/CLOSEDX", "social-window");
			});
			$j(".newsletter").bind("click", function() {
				alert("newsletter link");
			});
			$j(".profilePortrait").hover(
				function() {
					var src = $j(this).children("a").children("img").attr("src");
					src = src.replace(/-prt/, '');
					$j(this).children("a").children("img").attr("src", "" + src + "");
				},
				function() {
					var src = $j(this).children("a").children("img").attr("src");
					src = src.split(".");
					$j(this).children("a").children("img").attr("src", "" + src[0] + "-prt." + src[1] + "");
				}
			);
			$j("#storeLocator > h2").bind("click", function() {
				clsd.storesearch();
			});
			$j("#endStoreSearch").bind("click", function() {
				$j(".store").show();
				$j(".allstore").hide();
				$j("#locator").hide();
			});
			$j("#popinfo").live("click", function() {
				$j(this).hide();
			});
			$j("#language").change(function() {
				var l = $j(this).val(),
					u = document.location.href;
				function lngfrwd(v) {
					if (l === "en") {
						if (v) document.location.href = u[0];
					} else {
						if (v) document.location.href = u[0] + "-" + u[1];
						else document.location.href = document.location.href + "-" + l;
					}
				}
				if (u.search("-") !== -1) {
					u = u.split("-");
					u[1] = l;
					lngfrwd(l);
				} else {
					lngfrwd();
				}
			});
			$j("#clsdBaskButt").live("click", function() {
				$j("#popup").hide();
			});
			$j("#prodIconOne").bind("mouseover", function() {
				if (!$j("#prodImgOne").is(":visible")) {
					$j("#prodImgTwo").fadeOut(500, function() {
						$j("#prodImgOne").fadeIn(500);
					});
				}
			});
			$j("#prodIconTwo").bind("mouseover", function() {
				if (!$j("#prodImgTwo").is(":visible")) {
					$j("#prodImgOne").fadeOut("slow", function() {
						$j("#prodImgTwo").fadeIn("slow");
					});
				}
			});
		},
		gmap : function(address) {
			var lat,
				lng,
				map,
				mapicon,
				marker,
				geocoder = new google.maps.Geocoder();
			function renderMap() {
				// console.log("render " + lat + " x " + lng);
				var latlng = new google.maps.LatLng(lat, lng);
				var mapOptions = {
					zoom : 15,
					center : latlng,
					mapTypeId : google.maps.MapTypeId.ROADMAP
				}
				map = new google.maps.Map(document.getElementById("storeMap"), mapOptions);
				mapicon = new google.maps.MarkerImage(
					'http://closed.wardenclyffeproject.com/images/mapicon.png',
					new google.maps.Size(20, 32),
				    new google.maps.Point(0,0),
				    new google.maps.Point(0, 32)
				);
				marker = new google.maps.Marker({
					map : map,
					position : latlng,
					icon : mapicon,
					flat : true,
					visible : true
				});
			}
			geocoder.geocode({
				'address': address
				}, function(results, status) {
					results = results[0];
					lat = results.geometry.location.lat();
					lng = results.geometry.location.lng();
					renderMap();
				});
		},
		xfeedoutput : function(x) {
			var eo,
				pst,
				scrl;
			$j.ajax({
				url : "/feeds/allfeed_get.php?x=" + x + "&l=all",
				dataType : "json",
				success : function(data) {
					if (data.length > 0) {
						pst = location.hash.replace(/#/, "");
						for (i in data) {
							//(i % 2) ? eo = "odd" : eo = "even"; // 0 = even ... odd, eh?
							if (data[i].type === "flickr") {
								$j("#xFeedOutput").append("<div id='" + data[i].post_id + "' class='xFeedItem flickr'>" + 
									"<div>" +
										"<img src='" + data[i].image_url + "' width='348' class='left clear' />" +
										"<h2 class='x left'>" + data[i].post_title + "</h2>" +
										"<p class='date left'>" + data[i].date_posted + "</p>" +
									"</div>" +
								"</div>");
							} else {
								if (data[i].post_text !== null) {
									var linkStrt = data[i].post_text.search(/http:\/\//gi),
										linkEnd,
										link;
									if (linkStrt !== -1) {
										link = data[i].post_text.substr(linkStrt);
										linkEnd = link.search(/\s/);
										if (linkEnd !== -1) link = link.substr(0, linkEnd);
										data[i].post_text = data[i].post_text.replace(link, "<a href='" + link + "' target='_blank'>" + link + "</a>");
									}
									$j("#xFeedOutput").append("<div id='" + data[i].post_id + "' class='xFeedItem twitter'>" +
										"<div>" +
											"<p class='left'>&ldquo;" + data[i].post_text + "&rdquo;" +
											" <span class='date'>&mdash;" + data[i].date_posted + "</span></p>" +
										"</div>" +
									"</div>");
								}
							}
						}
						if (pst) {
							pst = $j("#" + pst + "");
							scrl = pst.offset();
							window.scrollTo(0, (scrl.top - 100));
							if (pst.hasClass("flicker")) pst.css("border-color", "#F21313");
							else pst.css("border-color", "#06AFFF");
						} 
					}
				}
			});
		},
		category : env.cat || null,
		parent_category : env.catPrnt || null,
		init : function() {
			if (!clsd.category) {
				clsd.shopcatnav();
				//var vrntC = vrnts || null;
				//if (vrntC) clsd.variants();
			}
			clsd.dropmenu();
			clsd.events();
		}
	};
	clsd.init();
});