jQuery(document).ready(function () {
	
	setTimeout(setSlider, 2000);
	
	// 
	if ($('.features_nav').length != 0) { assignTabs(".features_nav","#feature_pages",nav,div); }
	
	// slide features	
	if ($('.feature_slide_area').length != 0) {
		var sld = 0;
		var nof = ($('.slides').children().size() - 3);
		var intervalId = 0;
		
		$('.slide_right').click(function () {
			sld -= 1;
			if (sld < -nof) {
				sld = -nof;	
			}
			var xPos = sld * 172;
			$('.slides').animate({ left: xPos + 'px'});						  
		});
		
		$('.slide_left').click(function () {
			sld += 1;
			if (sld > 0) {
			 sld = 0;
			}
			var xPos = sld * 172;
			$('.slides').animate({ left: xPos + 'px'});						  
		});
		
		$('.slide').mouseover(function () {
			$(this).children('.overlay').css('display','block');
			clearInterval(intervalId);
		});
		$('.slide').mouseout(function () {
			$(this).children('.overlay').css('display','none');	
			intervalId = setInterval(nextSlide,6000);
		});
		
		function nextSlide () {
			sld -= 1;
			if (sld < -nof) {
				sld = 0;	
			}
			var xPos = sld * 172;
			$('.slides').animate({ left: xPos + 'px'});
		}
		
		intervalId = setInterval(nextSlide,6000);
	}
	
	// QS rollovers
	$('#qs1').mouseover(function () { $(this).attr('src','images/qs_home_1on.gif'); });
	$('#qs1').mouseout(function () { $(this).attr('src','images/qs_home_1.gif'); });
	$('#qs2').mouseover(function () { $(this).attr('src','images/qs_home_2on.gif'); });
	$('#qs2').mouseout(function () { $(this).attr('src','images/qs_home_2.gif'); });
	$('#qs3').mouseover(function () { $(this).attr('src','images/qs_home_3on.gif'); });
	$('#qs3').mouseout(function () { $(this).attr('src','images/qs_home_3.gif'); });
	

    // Dropdown nav functionality
    $("ul.dropdown li").hover(function () {
        if ($(this).hasClass('drop')) {
            $(this).addClass("hover");
            $('.sub_menu', this).css('visibility', 'visible');
			
			var str = $(this).children("a:first").text();
			if (str == "Sustainability") {
				$(this).children('.sub_menu').css('left', '-95px');
			}
			
			/*var tabWidth = $(this).css('width');
			tabWidth = tabWidth.replace("px", "");
			var center = Math.round((257 - tabWidth)/2) * -1;
			$(this).children('.sub_menu').css('left', center + 'px');*/
        }
    }, function () {
        if ($(this).hasClass('drop')) {
            $(this).removeClass("hover");
            $('.sub_menu', this).css('visibility', 'hidden');
        }
    });


    // Dropup nav functionality on details right column
    $(".menu a.menulink").hover(function () {
        $(this).next().show();
    }, function () {
        $(this).next().hide();
    });

    $(".menu ul").hover(function () {
        $(this).show();
    }, function () {
        $(this).hide();
    });

    /*$("div.menu a.menulink").hover(function () {
    $(this).next().show();
    }, function () {
    $(this).next().hide();
    });

    $("div.menu ul").hover(function () {
    $(this).show();
    }, function () {
    $(this).hide();
    });*/


    // FastTab dropdown functionality
    $(".fasttab a.btn-fasttab").hover(function () {
        $(this).next().show();
    }, function () {
        $(this).next().hide();
    });

    $(".fasttab div.fasttab-menu").hover(function () {
        $(this).show();
    }, function () {
        $(this).hide();
    });


    // Cart panel slide-down
    //var offsetleft = $("#header").offset();
    //$("div.btn_bg").css({ "left": ((offsetleft.left) + 773) + "px" });


    $("div.btn_bg").click(function () {
        $("div.panel-container").animate({ height: '326' }, 400)
        $("#openp").hide();
        $("#closep").show();
    });

    $("div#closep, a#btn-continue").click(function () {
        $("#closep").hide();
        $("#openp").show();
        $("div.panel-container").animate({ height: '0' }, 400);
    });

    // get url variables
    var urlvars = getUrlVars();

    // open cart is openpanel=true
    var byName = urlvars["openpanel"];
    if (byName) {
        $("div.panel-container").animate({ height: '326' }, 400)
        $("#openp").hide();
        $("#closep").show();
    }

    // set initial accordian value
    var accordian = Number(urlvars["tb"]);

    if (!urlvars["tb"]) {
        accordian = 0;
    }

    //Homepage What's New panel slide-down
    $("div.wn").click(function () {
        $("div#whats-new").animate({ height: '210' }, 200);
        $("#openwp").hide();
        $("#closewp").show();
    });
    $("div#closewp").click(function () {
        $("div#whats-new").animate({ height: '0' }, 200, function () {
            $("#closewp").hide();
            $("#openwp").show();
        });
    });

    /*
    //Homepage Product Search panel slide-down
    $("div.ps").click(function(){
    $("div.wn").css('z-index','50');
    $("#openps").hide(); $("#closeps").show();
    $("div#ps-container").animate({top:'8'}, 200);
    $("div#prod-search").animate({ height: '608'},200, function(){
    $("div.hm-features, div#whats-new").css('visibility','hidden');
    });
    });
	
    $("div#closeps").click(function(){
    $("div#ps-container").animate({top:'409'}, 200);
    $("div#prod-search").animate({ height: '0'},200, function(){
    $("#closeps").hide(); $("#openps").show();
    $("div.wn").css('z-index','200');
    $("div.hm-features, div#whats-new").css('visibility','visible');
    });
		
   		
    });
    */

    // Homepage FastTab dropdown functionality
    $(".hm-fasttab a.btn-hm-fasttab").hover(function () {
        $(".hm-fasttab a.btn-hm-fasttab img").attr("src", "/images/home/btn_hm_need_carpet_on.gif");
        $(this).next().show();
    }, function () {
        $(".hm-fasttab a.btn-hm-fasttab img").attr("src", "/images/home/btn_hm_need_carpet.gif");
        $(this).next().hide();
    });

    $(".hm-fasttab div.hm-fasttab-menu").hover(function () {
        $(".hm-fasttab a.btn-hm-fasttab img").attr("src", "/images/home/btn_hm_need_carpet_on.gif");
        $(this).show();
    }, function () {
        $(".hm-fasttab a.btn-hm-fasttab img").attr("src", "/images/home/btn_hm_need_carpet.gif");
        $(this).hide();
    });

    //forces a set width on the long jqtransform select inputs
    var myW = 445;
    $(".select-long").css("width", myW);
    $(".select-long").parents(".jqTransformInputWrapper").css("width", myW);

    //var myWW = 143;
    //$(".pc-ddl").css("width", 143);
    //$(".pc-ddl").parents(".jqTransformInputWrapper").css("width", myWW);	

    // test
    //$("#accordion").accordion({ collapsible: true, autoHeight: false, active: accordian });

    // remove extra div tags generated by .NET
    $("#ctl00_ContentPlaceHolder1_pnlSelectors").children().contents().unwrap();

    // set initial accordian value
    //var accordian = Number(urlvars["tb"]);

    if (!urlvars["tb"]) {
        var hiddenacc = $("#ctl00_ContentPlaceHolder1_hidAccordion").attr('value');
        var coordinatesExists = $("#acc3").attr('title');
        var visAccordion = 3;

        if (!hiddenacc) {
            accordian = 0;
            var title = $('#0').attr("title");
            var img = $('#0').attr("href");
            loadRight(img, title);
        } else {
            //alert("hiddenacc=" + hiddenacc);
            // load initial content on right
            if (hiddenacc == 'color') {
                accordian = 1;
            }
            if (!coordinatesExists) {
                visAccordion = 2;
            }

            if (hiddenacc == 'vis') {
                accordian = visAccordion;
            }
            if (hiddenacc == 'dnf') {
                accordian = visAccordion + 1;
            }
        }


        //alert(accordian);
    }

    // initialzie accordian and set default tab open
    $("#ctl00_ContentPlaceHolder1_pnlSelectors").accordion({ collapsible: true, autoHeight: false, active: accordian });
    $('#acc8').click(function () { location.href = $(this).attr('href'); return false; });

    // load initial content on right
    var title = $('#acc1').attr("title");
    var img = $('#acc1').attr("href");
    loadRight(img, title);

    $('#acc1').click(function () {
        var title = $(this).attr("title");
        var img = $(this).attr("href");
        loadRight(img, title);
    });

    $('#acc2').click(function () {
        document.getElementById("ctl00_ContentPlaceHolder1_hidAccordion").value = "color";
    });

    /* -- to handle a conflict between jqtransform and AJAX */
    var prm = Sys.WebForms.PageRequestManager.getInstance();
    prm.add_endRequest(function () {
        //$('.rowElem').jqTransform();
        $(".col1,.col2,.col3,.col4").jqTransform();

    });

    // set cluetips
    clueTipInit();

    // zoom gallery modal window functionality
    $("a.zoom").fancybox({
        'overlayOpacity': .75,
        'overlayColor': '#000'
    });	
});

function clueTipInit () {
	$('.load-local').cluetip({
        luezIndex: 97,
        positionBy: 'fixed',
        topOffset: -55,
        leftOffset: 30,
        local: true,
        hideLocal: true,
        cluetipClass: 'tmg',
        attribute: 'rel',
        showTitle: false,
        dropShadow: false,
		clickThrough: true,
        // settings for when hoverIntent plugin is used
        hoverIntent: {
            sensitivity: 3,
            interval: 50,
            timeout: 0
        }
    });
}

$(function () {
    //find all form with class jqtransform and apply the plugin
   	//$("form.jqtransform").jqTransform({ imgPath: 'images/form_elements/' });

    var tlength = 143;
    $(".textinput").css("width", tlength);
    $(".textinput").parents(".jqTransformInputWrapper").css("width", tlength);
});


// this solves a positioning problem with the Sample Cart button
$(window).resize(function () {
    //var offsetleft = $("#header").offset();
    //$("div.btn_bg").css({ "left": ((offsetleft.left) + 773) + "px" });
});

// parse URL variables
function getUrlVars() {
	var vars = new Array();
	var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
	 	
	for (var i = 0; i < hashes.length; i++) {
		hash = hashes[i].split('=');
		vars.push(hash[0]);
		vars[hash[0]] = hash[1];
	}
		
	return vars;
}

function loadViz(url) {
	$.ajax({
		url: url,
		cache: false,
		dataType: "html",
		success: function(html){
			$('.rightphoto').contents().remove();
			$('.rightphoto').append(html);
			$('.rightphoto').hide().fadeIn('slow');
			$("#visphotos").children(':first').show();
			$("#pnlDrag").children(':first').show();
			$('.rightphoto').contents().append("<script>$(\".menu a.menulink\").hover(function () {$(this).next().show();}, function () { $(this).next().hide(); });$(\".menu ul\").hover(function () {$(this).show();}, function () {$(this).hide();});</script>");
		}
	});
}

function loadColors (url) {
	$.ajax({
		url: url,
		cache: false,
		dataType: "html",
		success: function(html){
			$('.rightphoto').contents().remove();
			$('.rightphoto').append(html);
			$('.rightphoto').append("<script>$(document).ready(function() { $('a.load-local-2').cluetip({luezIndex: 97,positionBy: 'fixed',topOffset: -55,leftOffset: 0,local: true,hideLocal: true,cluetipClass: 'tmg',attribute: 'rel',showTitle: false,dropShadow: false,clickThrough: true,hoverIntent: {sensitivity: 3,interval: 50,timeout: 0}}); }); </script>");
			
			if ($('.rightphoto').contents().children(':last-child').is('#coordinatingColors')) {
				/*$('#coordinatingColors').contents().append("<script>$(document).ready(function() { $('a.load-local-2').cluetip({luezIndex: 97,positionBy: 'fixed',topOffset: -55,leftOffset: 0,local: true,hideLocal: true,cluetipClass: 'tmg',attribute: 'rel',showTitle: false,dropShadow: false,clickThrough: true,hoverIntent: {sensitivity: 3,interval: 50,timeout: 0}}); }); </script>");*/
			}
		}
	});
}

function loadRight (img, nm) {
	var html = "<div class=\"photo\"><img src=\"" + img + "\" alt=\"\" width=\"399\" /></div><div class=\"bar\"><div class=\"prod-name\">" + nm + "</div><!--<div class=\"zoom dots\"><a href=\"#\"><img src=\"images/zoom_out_off.gif\" alt=\"zoom out\" width=\"15\" height=\"15\" /></a><a href=\"#\"><img src=\"images/zoom_in_off.gif\" alt=\"zoom in\" width=\"15\" height=\"15\" /></a></div>--></div>";
	
	$('.rightphoto').contents().remove();
	$('.rightphoto').append(html);
	$('.rightphoto').hide().fadeIn('slow');
}

function setcolorid(id) {
    document.getElementById("ctl00_ContentPlaceHolder1_hidColorNumber").value = id;
    document.getElementById("ctl00_ContentPlaceHolder1_hidAccordion").value = "color";
    $('.load-local').removeClass('selected');
    document.getElementById("thumbImg_" + id).className = "load-local selected";
	//alert($("#ctl00_ContentPlaceHolder1_hidColorNumber").attr("value"));
}

function setVisid(id) {
    document.getElementById("ctl00_ContentPlaceHolder1_hidColorNumber").value = id;
    document.getElementById("ctl00_ContentPlaceHolder1_hidAccordion").value = "vis";
    $('[id^="visImg_"]').removeClass('selected');
    var visImg = document.getElementById("visImg_" + id);
    if (visImg) {
        visImg.className = "load-local selected";
    }
}

function setDnfid(id) {
    document.getElementById("ctl00_ContentPlaceHolder1_hidColorNumber").value = id;
    document.getElementById("ctl00_ContentPlaceHolder1_hidAccordion").value = "dnf";
    $('[id^="dnfImg_"]').removeClass('selected');
    var dnfImg = document.getElementById("dnfImg_" + id);
    if(dnfImg)
    {
        dnfImg.className = "load-local selected";
    }

}


function closecart() {
	$('.check').hide();
    //targetContent();
}

// target content after order sample button click
function targetContent() {
    //var active = $( "#ctl00_ContentPlaceHolder1_pnlSelectors" ).accordion( "option", "active" );
    var colorId = document.getElementById("ctl00_ContentPlaceHolder1_hidColorNumber").value;
    var nm = document.getElementById("ctl00_ContentPlaceHolder1_hidAccordion").value;
    //alert("Targeting" + nm + colorId);
    if (nm == "color") {
        loadColors("colors.aspx?thisColorId=" + colorId);
    }

    if (nm == "vis") {
        loadViz("visualizer.aspx?thisColorId=" + colorId);
        //setVisid(colorId);
    }

    if (nm == "dnf") {
        loadViz("dragnfly.aspx?thisColorId=" + colorId);
        //setDnfid(colorId);
    }
}

// a function that shows content upon select input change
function showcontent(id) {
	$('.select-content').hide();
	$('#'+id).show();
}

// visualizer functions
	function setvisInstall(inst) {
	    document.getElementById("ctl00_ContentPlaceHolder1_hidInstall").value = inst;
        displayVisImage();
        return false;
    }
    function setvisRoom(rm) {
        document.getElementById("ctl00_ContentPlaceHolder1_hidRoom").value = rm;
        displayVisImage();
        return false;
    }
    function displayVisImage() {
        var inst = document.getElementById("ctl00_ContentPlaceHolder1_hidInstall").value;
        var rm = document.getElementById("ctl00_ContentPlaceHolder1_hidRoom").value;
        var clr = document.getElementById("ctl00_ContentPlaceHolder1_hidColorNumber").value;
        if (inst != "" && rm != "" && clr != "") {
             $(".visImage").hide();
             var visImageId = "visImage" + clr + inst + rm;
             $("#" + visImageId).show();
            }
    }
    function download() {
        var inst = document.getElementById("ctl00_ContentPlaceHolder1_hidInstall").value;
        var rm = document.getElementById("ctl00_ContentPlaceHolder1_hidRoom").value;
        var clr = document.getElementById("ctl00_ContentPlaceHolder1_hidColorNumber").value;
        //alert(inst + rm + clr);
        if (inst != "" && rm != "" && clr != "") {
            var visImageId = "visImage" + clr + inst + rm;
            var myimg = document.getElementById(visImageId);
            var myAnchor = document.getElementById("downloadfile");
            var visImageSrc = myimg.src;
            visImageSrc = visImageSrc.replace("_s.jpg", ".jpg");
            visImageSrc = visImageSrc.replace(window.location.protocol + "//", "");
            visImageSrc = visImageSrc.replace(window.location.host, "");
            var myURL = window.location.protocol + "//" + window.location.host + "/download.aspx?file=" + visImageSrc;
            myAnchor.href = myURL;
            myAnchor.target = "_new";
        }
        return false;
    }
	
// dragandfly functions
	function setdrag(divid) {
        $(".right-dnfgroup").hide();
        $("#" + divid).show();
        return false;
    }

// drop down function for Quickship PDF Download

function selectdropcontent(id) {
	window.open(id, "_self");	
}

	// feature slides
	var nav = new Array();
	var div = new Array();

	// function to create tabs
	function assignTabs (tab, con, nav, div, init) {
		$(tab + ' ul').children().each( function (index) {			
			// add to nav array
			nav[index] = $(this);
			
			//$(nav[pg]).children("a").attr("href") != "#"
			
			// assign click
			$(this).click(function () {
				pg = index;
				tabhilite(tab, pg, nav, div);
			});
			
			/*$(this).mouseover(function () {
				$(this).addClass("on");							
			});
			$(this).mouseout(function () {
				$(this).removeClass("on");							
			});*/
			
		});
		
		$(con).children().each( function (index) {
			div[index] = $(this);									  
		});
		
		if (init) {
			tabhilite(tab, init, nav, div);
		} else {
			// initialize
			tabhilite(tab, 0, nav, div);
		}
	}
	
	// function to select and hilite tabs
	function tabhilite (tab, pg, nav, div) {
		var i;
		$(tab).css('display','block');
		for (i = 0; i < nav.length; i++) {
			if (i == pg && $(nav[pg]).children("a").attr("href") != "#") {
				
			} else {
				if (i == pg) {
					if (div) {
						$(nav[pg]).addClass("on");
						$(div[pg]).fadeIn();
					} else {
						alert("NO!");	
					}
				} else {
					if (div) {
						$(nav[i]).removeClass("on");
						$(div[i]).hide();
					} else {
						alert("NO!");	
					}
				}
			}
		}
	}
	
	slides = new Array();
	var slide_buttons = new Array();
	var destinations = new Array();
	sld = null;
	var busy = false;
	timer = null;
	
	function setSlider () {		
		// get the number of slides
		var slide_num = $('.content_slides').children().size();
		
		// slide buttons
		var buttons = "";
		
		// create a button for each slider and make the entire slider box clickable
		$('.content_slides').children().each( function (index) {			
			// add to slides array
			slides[index] = $(this);
		});
		
		sld = slides.length - 1;
		
		// pause
		$('#content_main').mouseover(function () {
			clearInterval(timer);
		});
		
		// restart
		$('#content_main').mouseout(function () {
			setTimer();
		});
		
		/*$('.controller_unit').mouseover(function () {
			$('.controller_left').fadeIn("slow");
			$('.controller_right').fadeIn("slow");										   
		});
		
		$('.controller_unit').mouseout(function () {
			$('.controller_left').fadeOut("slow");
			$('.controller_right').fadeOut("slow");										   
		});*/
		
		// initialize buttons
		slideShow(sld);
		
		// start timer
		setTimer();
		
		// set controller
		$('.controller_left').click(function () {
			gotoSlide(1);								  
		});
		
		$('.controller_right').click(function () {
			gotoSlide(-1);						  
		});
		
		$('.controller_left').mouseover(function () {
			$(this).addClass("on");										   
		});
		
		$('.controller_left').mouseout(function () {
			$(this).removeClass("on");										   
		});
		
		$('.controller_right').mouseover(function () {
			$(this).addClass("on");										   
		});
		
		$('.controller_right').mouseout(function () {
			$(this).removeClass("on");										   
		});
		
		$('.component_info').css('display','block');
	}
	
	function slideShow (pg) {
		/*if (sld == null || sld == undefined) {
			sld = slides.length;
		}*/
		
		if (pg == null || pg == undefined) {
			pg = sld;
		}
		
		// transition
		if (pg < 1) {
			
			pg = slides.length - 1;
			
			$(slides[pg]).fadeIn("slow", function () {
				$.each(slides, function () {
					$(this).css("display","block");											 
				});
			});
			sld = pg;
		} else {
			$(slides[pg]).fadeOut("slow", function () {
											
			});
			sld -= 1;
		}

	}
	
	function gotoSlide (inc) {
		/*if (sld == null || sld == undefined) { sld = slides.length - 1; }*/
		clearInterval(timer);
		
		if (inc < 0) {
			if (sld > 0) {
				$(slides[sld]).fadeOut("slow");
				sld -= 1;
			} else {
				$(slides[slides.length - 1]).fadeIn("slow", function () {
					$.each(slides, function () {
						$(this).css("display","block");											 
					});
				});
				sld = slides.length - 1;
			}
		} 
		if (inc > 0) {
			if (sld < slides.length - 1)  {
				sld += 1;
				$(slides[sld]).fadeIn("slow");
			} else {
				$.each(slides, function (index) {
					if (index == slides.length - 1) {
						$(this).fadeOut("slow");
					} else if (index == 0) {
						
					} else {
						$(this).css("display","none");
					}
				});
				sld = 0;
			}
		}
	}
	
	function setTimer () {
		timer = setInterval("slideShow()",6000);
	}
	
	function newAlert (msg) {
		$('#band').contents().remove();
		$('#band').append(msg);
	}
