$(function(){

// updated index (root)	   
setCurrPage = function(){
	var indexOfNav, nameOfPage, foundPage = false,
	curURL = window.location.toString().toLowerCase();
	//getRefinedLoction = curURL.substring(25)
	arrayOfPages = ["index", "products","specials", "faq"];
	for(var i=0; i<arrayOfPages.length; i++){
		if(curURL.match(arrayOfPages[i])){
			indexOfNav = i;
			nameOfPage = arrayOfPages[i];
			foundPage = true;
		 }
	
		}
	if(foundPage){
		$("body").addClass(nameOfPage);
        $("#topNav > li").eq(indexOfNav).addClass("active");

	}
		
		
	if(curURL.match(arrayOfPages[0]) || location.pathname.substr(-1) === "/"){
		$("body").addClass("index");
		rV.init();
		doAnimate = setInterval(testimonialsBelt.animate,8000);
		emailSignUp();
		$("#topNav > li").eq(0).addClass("active");

		}		

	if(curURL.match(arrayOfPages[1])){
		pv.initSetUP();
		giveColorValues();
        // figure out why passing in setTimeout("pv.preLoad()",3500); didnt work
        var preLoad = function(){pv.preLoad();};
		setTimeout(preLoad,3500);
        quoteFunct();
        
        
        // track sort sale page
        var pageTracker = _gat._getTracker("UA-2822768-3");
if (pageTracker) {
	
$(".trackListItem").bind('click', function() {
          pageTracker._trackEvent('click', "list click", "in-pageIneraction");
          _gaq.push(['_trackEvent', 'click', 'list click', 'in-pageIneraction']);

      });
	
	
$("#sortContainer > a").bind('click', function() {
          pageTracker._trackEvent('click', "sorted sale", "in-pageIneraction");
          _gaq.push(['_trackEvent', 'click', 'sorted sale', 'in-pageIneraction']);

      });


// select sort TODO..  get sort value
$("#sortContainer > select").bind('change', function() {
          pageTracker._trackEvent('change', "sorted", "in-pageIneraction");

      });
      
 
 
      
      
    $("#searchGo").bind('click', function() {
          pageTracker._trackEvent('click', "search", "searched");

      });
		
		}
}
	};
    
    
var quoteFunct = function(){   
$("#center").delegate(".triggerQuote","click",function(e){

    var jThis = $(this),
        pos = jThis.position(),
        quoteWrapper = "quoteWrapper";
        if($("."+quoteWrapper).length >= 1){
         $("."+quoteWrapper).css({top:pos.top-450,left:pos.left+200});
         return; 
        }
        $("<div/>").addClass(quoteWrapper).css({top:pos.top-450,left:pos.left+200}).load("includes/quoteForm.html",function(){
         $("."+quoteWrapper).find("#quoteSKU").val($("#section-header h2 span").text());
        }).appendTo("#center").fadeIn(300).find("#quoteSKU").val($("#section-header h2 span").text());
        }).delegate("#exitQuote","click",function(){
            $(".quoteWrapper").fadeOut(500, function(){
            $(".quoteWrapper").remove();
        });
    }).delegate("#formQuote","submit",function(){
        var serialized = $(this).serialize(),
        hasConactName = $("#quoteName").val().length? true :false,
        hasASI = $("#quoteASI").val().length? true :false,
		validEmail = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test($("#quoteEmail").val());
		
		$("#quoteName").parent().toggleClass("error",!hasConactName);
		$("#quoteASI").parent().toggleClass("error",!hasASI);
		$("#quoteEmail").parent().toggleClass("error",!validEmail);
		var doSubmit = hasConactName && hasASI && validEmail;
		if(doSubmit){
            $.ajax({
                type: 'POST',
                url: "includes/quoteHandler.php?"+serialized,
                beforeSend:function(){
                   $("<div>Submitting Quote....</div>").appendTo("#formQuoteContainer");
                },
                success: function(data,textStatus){
                $("#formQuoteContainer").html(data);
            }
        });
        }    
    return false;
});
};



var startInterval,
	 rV = {};
	// SETTING GLOBAL VAR'S
	rV.container = $("#contentRotator");
	rV.containerEl = rV.container.children();
	rV.containerElSize = rV.containerEl.length;
	rV.last = 0;
	rV.next = 1;
	rV.looped = false;
	rV.speed = 2000; 
	rV.interval = 6000; 
	rV.clickFade = 300;
	rV.isPaused = false; 

	rV.setUpNav = function(){
		
		 navContainer = $("<div>").addClass("navContainer");
		   for(i=1; i<rV.containerElSize+1; i++){
			navContainer.append($("<span>"+i+"</span>"));
			}
			 rV.pauseButton = $("<div>")
				.addClass("pauseButton")
				.html("pause")
				.appendTo(navContainer)
				.click(function(){
					if(!rV.isPaused){
													clearInterval(startInterval);
													rV.pauseButton.html("Play");
													rV.isPaused = true;
													}
												else{
													rV.slideInterval(); 
													startInterval = setInterval(rV.slideInterval,rV.interval);
													rV.pauseButton.html("pause");
													rV.isPaused = false;
													}	
											 });
										rV.container.parent().append(navContainer); 
										var navFunc = navContainer.children().eq(0).addClass("current").end().end().find("span").click(function(){
										clearInterval(startInterval)
										$(this).siblings().removeClass("current");
										$(this).addClass("current");
										
										indexOfClicked = navFunc.index($(this));
										//changed this line for smoother transition
										rV.containerEl.eq(indexOfClicked === rV.last?rV.containerElSize+100:rV.last).fadeOut(rV.clickFade);
										rV.containerEl.eq(indexOfClicked).fadeIn(rV.clickFade, function(){rV.containerEl.eq(indexOfClicked).css("opacity",1)});
										
										
										
										rV.last = indexOfClicked;
										rV.next = indexOfClicked==rV.containerElSize-1?0:indexOfClicked+1;
										rV.pauseButton.html("Play");
										rV.isPaused = true;

								})

		    }
		
		rV.slideInterval = function(){
			rV.containerEl.eq(rV.last).fadeOut(rV.speed);
			rV.containerEl.eq(rV.next).fadeIn(rV.speed);			
			$(".navContainer span").removeClass("current")
			$(".navContainer span").eq(rV.next).addClass("current")
			rV.last++
			rV.next++
			
			if(rV.looped){
				rV.looped = false
				rV.last = 0;
				rV.next = 1;
				
				}
			if(rV.last==rV.containerElSize-1){
				rV.last = rV.containerElSize-1;
				rV.next = 0;
				rV.looped = true
			}
		}
	
		
	rV.init = function(){
			rV.containerEl.filter(":not(:first)").css("display","none");
			rV.setUpNav()
			navContainer.children(":last").addClass("test")
			startInterval = setInterval(rV.slideInterval,rV.interval)		
		}		




var emailSignUp = function(){
	var resetEmail = function(){
    $("#emailSucsessMsg").slideUp(300);
    $("#signUpForm").slideDown(300);
     $("#emailText").val("Email Address");
     $("#asiVal").val("ASI#");
}
    
	$("#signUpForm").submit(function(){
   var  emailVal = $("#emailText").val(),
	  asiVal = $("#asiVal").val();
	// validate		
$.ajax({
	 type: 'GET',
      url: "includes/updateEmailUsers.php?email="+emailVal+"&ASI="+asiVal,
  success: function(data,textStatus){
		$("#emailSucsessMsg").html(data).slideDown(500)
		$("#signUpForm").slideUp(500,function(){
        setTimeout(resetEmail,2500);
        });
	}	 
})	
 return false
	})
	$("#emailText").click(function(){
		$(this).val("")		   
	})
	}






				
	var noOfAnim = 0,
		isRunning = false,
		animSpeed = 2700,
		intervalSpeed = 8000,
		isInFullView = false,
		isAnimating = false,
		giveMeHeight,
		doAnimate;
		
	var testimonialsBelt={
				parentElment:$("#testimonialsCntnr ul"),
				childrenElem:$("#testimonialsCntnr ul li"),
				childrenElemLength:$("#testimonialsCntnr ul li").length,
				getCurItemHeight:function(curitemAnim){
					 giveMeHeight = $("#testimonialsCntnr ul li").eq(curitemAnim).height();
					return giveMeHeight;
				},
				animate:function(){
					var animAmmount = testimonialsBelt.getCurItemHeight(noOfAnim)+50;
					testimonialsBelt.parentElment.animate({top:"-="+animAmmount+"px"},animSpeed);
					noOfAnim++;
					isRunning=true;
					testimonialsBelt.updateBelt();
				},
				updateBelt:function(){
					var updatedList = $("#testimonialsCntnr ul li");
					var cloneCurnt = updatedList.eq(noOfAnim).clone();
					testimonialsBelt.parentElment.append(cloneCurnt);
					if(noOfAnim > (testimonialsBelt.childrenElem.length+20)){
					  testimonialsBelt.resetBelt();
					   }
				},	
				resetBelt:function(){
					clearInterval(doAnimate);
					noOfAnim=0;
					isRunning=false;
					$(".testimonialsCntnr ul li")
						.eq(testimonialsBelt.childrenElemLength)
						.nextAll()
						.remove();
					if(!isInFullView){
						testimonialsBelt.parentElment.animate({top:"0"},500);
						doAnimate = setInterval(testimonialsBelt.animate,intervalSpeed)	
					  }
				}
		}
	// this section is updated see the wraped in a if() was needed for the new expanding testimonals
		testimonialsBelt.parentElment.hover(
		   function () {
		if(!isInFullView){
			  isRunning=false;
			  clearInterval(doAnimate);
			  $(this).stop();
			  }
		}, 
		function() {
		if(!isInFullView){
		 	 doAnimate = setInterval(testimonialsBelt.animate,intervalSpeed);
    		 isRunning=true;
			}
		  }
	);	
		
	//initi the belt	
	
			





	
	

var context 	=		$("#content"),
	listOflinks =  		$(".entries-list li", context),
	lrgImg = 			$("#mediumImg"),
	lengthOfProducts =	listOflinks.length,
	preNav = 			$(".entry-previous",context),
	nextNav= 			$(".entry-next",context),
	currentInView =		0,
	sectionHeader = 	$("#section-header h2"),
	startUpImg =		 "images/startUp.png",
	current,
	clickedOn,
	priceTable = 		$("#priceTable"),
	scrollContainer = 	$(".scroll-wrapper", context),
	buttonUp =			$("#scrollUp"),
	buttonDown =		$("#scrollDown"),
	currPos = 			0,
	maxScroll = 		listOflinks.eq(0).height()*lengthOfProducts-495,
	getHash = 			window.location.hash,
	refinedHash =       getHash.replace(/-pen/img,"")
	currHotPen = 		"CC-011"
	//takeRandomPen	= Math.random()

		
 var pv = {
	initSetUP: 		function(){	
						//sectionHeader.html("Penline pen viewer");
						//pv.updateNav(-1,0);
						//current = -1;

/*context.delegate("li","click",function(e){*/
					listOflinks.live(/*hover*/ "click",function(e){
						clickedOn = $(this)
							pv.listClick(e);
					    	return false
						});
						if(getHash){
							$(" "+refinedHash+" ").click();
							//Please add animate to product
							}
						else{
							$(".entries-list li:eq(0)>div").click();
                            //("#"+currHotPen).click()
							//Please add animate to product
							//lrgImg.attr("src",startUpImg)
							}
							
						pv.setUpScrollerButtons();

// search for keyword						
$("#sortContainer").find("select").val("Default").change(function(){
$("#sortContainer>a").removeClass("selected");

$("#searchText").val(" ")
    var valueSelected = $(this).val();
    $.ajax({
        type: 'GET',
        dataType:"html",
        url: "includes/SortProdAjax.php?sortBy="+valueSelected,
        success: function(data,textStatus){
        pensList = $(".entries-list");
        pensList.fadeTo(400, .0, function(){
            pensList.html(data);
            })
        },
        complete:function(){
            pensList.fadeTo(500, 1, function(){
                pv.sortedComplete();
                giveColorValues();
            });
        }
    })
})

// sort pens 
$("#sortContainer").find("a").click(function(){
	var saleButton = $(this);
	if(!saleButton.hasClass("selected")){
	   saleButton.addClass("selected");
	   $(".entries-list").find("> li").not(".sale").slideUp(1000, function(){
            $(".sale").eq(0).click();
        });
	} else{
		saleButton.removeClass("selected");
	   $(".entries-list").find("> li").slideDown(700);
	   $("#sortContainer").find("select").trigger("change");
		}
		return false
	});				

      
// search      


$("#loading").ajaxStart(function(){
   $(this).show();
 });
$("#loading").ajaxStop(function(){
   $(this).hide(2000);
 });




						
						
					},
	     	preLoad: function(){
				var entriesList = $(".entries-list").find("img");
				   for(var i=0; i<entriesList.length; i++ ){
					   var newImage = new Image();
					  	   newImage.src = entriesList[i].src.replace(/small/,"medium");
					   }
				
				},				
setUpScrollerButtons:function(){
						buttonUp.click(function(){
								scrollContainer.animate({"scrollTop":"-=400px"},500)											
								})
						
						buttonDown.click(function(){
								scrollContainer.animate({"scrollTop":"+=400px"},500)
												
								});
						
						scrollContainer.scroll(function () { 
						currPos = scrollContainer.scrollTop()
							if(currPos > maxScroll){
								 buttonDown.addClass("inActive");
								}
							else{
								buttonDown.removeClass("inActive")
							}
							if(currPos == 0){
								buttonUp.addClass("inActive");
								}
							else{buttonUp.removeClass("inActive")}
						
						});				

},
	 updateAll:		function(getCurr){
						prev=getCurr-1;
						next=getCurr+1;
						pv.updateNav(prev,next);
						skuValue = listOflinks.eq(getCurr).attr("id");
						penNameValue = listOflinks.eq(getCurr).find(".prodName",context).html();
						pv.updateCaption(penNameValue,skuValue);
		 			},
	 updateNav:		function(prev,next){
		 				preNav.add(nextNav).unbind("click");
						if(prev >= 0){preNav.attr("rel",prev).click(function(){pv.navClick(prev);pv.animScroll(prev)})
							preNav.parent().removeClass("inactive");
						}
					 	else{preNav.parent().addClass("inactive")}
						if(next < lengthOfProducts){nextNav.attr("rel", next).click(function(){pv.navClick(next);pv.animScroll(next)}); 
							nextNav.parent().removeClass("inactive")}
						else{nextNav.parent().addClass("inactive")};
	 				
					 },
	navClick:		function(arg){
		 				listOflinks.removeClass("active");
						skuVal = listOflinks.eq(arg).attr("id");
						penNameVal = listOflinks.eq(arg).find(".prodName",context).html();
						pv.showCurr(arg,skuVal);
						pv.updateCaption(penNameVal,skuVal);
						return false
					 },
	listClick:		function(e){
						listOflinks.removeClass("active");
						//alert(clickedOn.attr("id"))
						clickedOn.addClass("active");
						getIndexHelper = listOflinks.filter(".active");
						current = listOflinks.index(getIndexHelper);
						passImgSrc = listOflinks.eq(current).attr("id");
						pv.showCurr(current,passImgSrc)
						return false
					 },			 
	 updateCaption:	function(penName,sku){sectionHeader.html(penName+"<span>"+sku+"</span>")},
	 showCurr:		function(curr, pasdCur){lrgImg.attr("src","prodImages/medium/"+$.trim(pasdCur)+".png");
						if (curr > -1){listOflinks.eq(curr).addClass("active")};
						current = curr;
						pv.updateAll(current);
		    			priceListContent = listOflinks.eq(curr).find(".additPenInfo",context).clone();
						//imrintAreaInfo = listOflinks.eq(curr).find(".additPenInfo .imprintInfo",context).clone();
						//$("li.imprintArea",context).html(imrintAreaInfo)
			    		priceTable.html(priceListContent).children().show();
						if(pasdCur){window.location.hash = $.trim(pasdCur)+"-pen"
						productName = $("#"+pasdCur).find(".prodName").text();
						document.title = "ThePenLine.com ASI #35592, the '"+productName+"' collection, ID=" + $.trim(pasdCur)
						};
						return false
					  },
	animScroll:		function(to){
						scrolltoMath  =  to*listOflinks.eq(1).height();
						scrollContainer.animate({"scrollTop":scrolltoMath},500)
					},
					
	sortedComplete:function(){
					context 	=		$("#content"),
					listOflinks =  		$(".entries-list li", context),
					lrgImg = 			$("#mediumImg"),
					lengthOfProducts =	listOflinks.length,
					preNav = 			$(".entry-previous",context),
					nextNav= 			$(".entry-next",context),
					currentInView =		0,
					sectionHeader = 	$("#section-header h2"),
					priceTable = 		$("#priceTable"),
					scrollContainer = 	$(".scroll-wrapper", context),
					currPos = 			0,
					maxScroll = 		listOflinks.eq(0).height() *lengthOfProducts-495,
					currHotPen = 		"CC-011"
					// animate scroll to top
					pv.animScroll(-90);
					// simulate a click on the first one
					listOflinks.eq(0).click();
					
					}
 		}
	 
	 //init

giveColorValues = function(){		   
$(".entries-list li").each(function(){
	$thisColors = $(this).find(".colorPlacholder")
	arrayOfColors = $thisColors.attr("id").toString().split(" ");
	for(c in arrayOfColors){
		$("<span>").css("background", arrayOfColors[c]).attr("title", arrayOfColors[c]).appendTo($thisColors)
	   }
	})	
// shift color taking to JS to minimze Page and adding exsiting ","

}


	setCurrPage();  
});



