// Website
jQuery(document).ready(function()
    {
        jQuery(".JScriptHideButtons") .each(function(i, obj)
        {
            var thisItem = jQuery(".itemFF2", this); //Called this in HorizontalCatalogItemsList
            if (thisItem.length == 0) {
                thisItem = jQuery(".HorizontalProductsListItem", this);
            }
            var count = thisItem.length;
            var itemWidth = thisItem.outerWidth(true);
            var viewportWidth = jQuery(".viewport").innerWidth();
            var itemsVisible = Math.round(viewportWidth / itemWidth);
            //alert(' viewportWidth: '+ viewportWidth +' itemWidth: '+ itemWidth +' itemsVisible=' + itemsVisible);
            if (count <= itemsVisible)
            {
                jQuery(".rightButton", this).css("visibility", "hidden");
                jQuery(".leftButton", this).css("visibility", "hidden");
            }
            else
            {
                enableScrollButtons( count, itemsVisible, itemWidth, this );
            }
        });
   			
   		
        $("#PrdHndlFrm input").click(function(i, obj) {
            $("#SubmitErrorText").hide();
        });
		
		
        $("#PrdHndlFrm").submit(function() {
		
            var checkedCount =0;
				
            $("#PrdHndlFrm input").each(function(i, obj) {
                if (this.checked)	checkedCount++;
            });
		
            if (checkedCount >0)
            {
                $("#SubmitErrorText").text("Please select a size!").hide();
						
                cartPopup("/sc/cartsummary");
                
                return true;
                
//overlay popup                
//                var data = "";
//                var inputs = jQuery( '#PrdHndlFrm input' );
//                for( var i = 0; i < inputs.length; i++ )
//                {
//                    if( jQuery(inputs[i]).attr('name') != 'Display' && jQuery(inputs[i]).attr('checked') )
//                    {
//                        if( data.length > 0 )
//                        {
//                            data += "&";
//                        }
//                        data += jQuery(inputs[i]).attr('name')  + "=" + escape( jQuery(inputs[i]).attr('value') );
//                    }   
//                }
//                cartPopup(jQuery('#PrdHndlFrm').attr('action'), data);
//                return false;
            }
            else
            {
                $("#SubmitErrorText").text("Please select a size!").show();
		
                return false;
            }
        });

		
        if (jQuery("#video").length > 0)
        {
            $('.product #video').show();
            insertFlash();
            $(".flash-ready").show();
				
            createVideoLink();
				
            toggleVideo('Flip to image viewer', true);
        }
        else
        {
			
        }
	
        changeBagItFormSubmit();

        jQuery("a.jscriptAppendReturnState").click(function() {
            appendReturnStateInfoToLink(this);
        });

        jQuery("form.jscriptAppendReturnState").submit(function() {
            appendReturnStateInfoToForm(this);
        });
            
        setScrollPosition();

    });
//= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
/*
 * Adds this to the link being actioned - scrollX=999 & scrollY=999
 * */
function appendReturnStateInfoToLink(thisLink) {
    //alert("appendReturnStateInfoToLink: start thisLink.href: " + thisLink.href);
    var hrf = new String(thisLink.href);
    if (! isThisALinkToUs(hrf)) {
        //alert("appendReturnStateInfoToLink: not a link to us");
        return;
    }
    //alert(hrf + ' indexOf: ' + hrf.indexOf('scrollX') + ' , ' + hrf.indexOf("returnToUrl"));

    if (hrf.indexOf("scrollX") > 0 ) {
        //They are here already. Back button was used or page links to itself (search does this).
        //We should update the parms but thats lots of code so we just return.
        //In general if a page re=displays itself it is probably after a form
        //submission which appendReturnStateInfoToForm handles.
        //
        //alert("appendReturnStateInfoToLink: already done");
        return;
    }

    var scrollCoordinates = getScrollCoordinates();
    //alert("appendReturnStateInfoToLink: 2 page tagged. scrollX,Y="+ scrollX +", "+ scrollY);

     if (hrf.indexOf("?") < 0) {
         hrf += "?";
     } else {
         hrf += "&";
     }
     hrf += "scrollX="+ scrollCoordinates[0]
          +"&scrollY="+ scrollCoordinates[1];
     thisLink.href = hrf;
     //alert("appendReturnStateInfoToLink: done - href: " + thisLink.href);
}

// Adds fields scrollX scrollY to the form being submitted
function appendReturnStateInfoToForm(thisForm) {
    //alert("appendReturnStateInfoToForm: thisForm: " + thisForm);
    var scrollCoordinates = getScrollCoordinates();

    if (jQuery("[name=scrollX]").length > 0
     && jQuery("[name=returnToUrl]").length > 0) {
        //alert("appendReturnStateInfoToForm: returnToUrl already there");
        return;
    } else {
        //alert("Adding the returnToUrl fields");
        jQuery(":last", thisForm).append(
        "<div><input type='hidden' name='scrollX' value='" + scrollCoordinates[0] +"' />"
           + "<input type='hidden' name='scrollY' value='" + scrollCoordinates[1] +"' /></div>");
    }
}

function isThisALinkToUs(link) {
    var result = false;
    if (link.indexOf("http:") < 0) {
        result = true;
    }
    if (link.indexOf("http://www.chemical-records") == 0) {
        result = true;
    }
    //alert("isThisALinkToUs: link: "+ link + "    result: "+ result);
    return result;
}

//From http://www.4guysfromrolla.com/articles/111704-1.aspx
function getScrollCoordinates() {
    //alert("getScrollCoordinates: start (WebSite)");
    var scrollX, scrollY;
    if (document.all) {
        if (document.documentElement.scrollLeft)
            scrollX = document.documentElement.scrollLeft;
        else
            scrollX = document.body.scrollLeft;
        if (document.documentElement.scrollTop)
            scrollY = document.documentElement.scrollTop;
        else
            scrollY = document.body.scrollTop;
    } else {
        scrollX = window.pageXOffset;
        scrollY = window.pageYOffset;
    }
    return [scrollX, scrollY];
}

// Scroll to position given by values in the http session. Fetch them from a servlet
function setScrollPosition() {
    //alert("setScrollPosition: start (ShopWeb)");
    if (jQuery(".jscriptAppendReturnState").length > 0) {
        jQuery.get( "/sc/ajax/GetScrollCoordinatesAjax", null,
            function xxxScrollPosition(returnedData) {
                //alert("xxxScrollPosition: start. returnedData: " + returnedData);
                var ix = returnedData.indexOf("$");
                if (ix > -1) {
                    var scrollX = returnedData.substring(0, ix);
                    var scrollY = returnedData.substring(ix+1);
                    //alert("xxxScrollPosition: 2: scroll to - x: "+ scrollX +" y: "+  scrollY);
                    window.scrollTo(scrollX, scrollY);
                }
            },
            "text" );
    }
}
//= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
function enableScrollButtons( count, itemsVisible, itemWidth, container )
{

    var showing = 0;

    jQuery(".leftButton", container).click(function()
    {
        showing-= itemsVisible;

        if (showing < 0)
        {
            if( showing > -itemsVisible )
            {
                showing = 0;
            }
            else
            {
                showing = count - itemsVisible;
            }
        }

        jQuery(".viewport", $(this).parent().get(0)).animate({
            scrollLeft: (showing * itemWidth)
        }, 1000);
    //alert('count='+ count +' itemsVisible=' + itemsVisible +' showing='+ showing);
    });

    jQuery(".rightButton", container).click(function()
    {
        showing+= itemsVisible;

        if (showing >= count)
            showing = 0;

        jQuery(".viewport", $(this).parent().get(0)).animate({
            scrollLeft: (showing * itemWidth)
        }, 1000);
    //alert('count='+ count +' itemsVisible=' + itemsVisible +' showing='+ showing);
    });
}

function createVideoLink()
{
    var videoLink = document.createElement("A");
    $(videoLink).text("Flip to video");
    $(videoLink).attr("href", "javascript:toggleVideo('Flip to image viewer')");
    $("#video-link").addClass("available");
    $("#video-link").empty().append(videoLink);
} 	
 	
function toggleVideo(newText, onPageLoad) 
{
    var selector = "#video-link a";
    var currentText = $(selector).text();

    // Find out if installed version of flash player is compatible
    var hasRequiredVersion = DetectFlashVer(requiredFlashVersion.majorVersion, requiredFlashVersion.minorVersion, requiredFlashVersion.revision);

    if(hasRequiredVersion)
    {
        if(currentText.match('video'))
        {
            $("#main-image #video").show();
							
            if(!onPageLoad && $.browser.msie)
            {
                var obj = $("#main-image .flash-ready").children("object");
                if(obj != null && obj.size() > 0&& obj.get(0).doResume)
                {
                    obj.get(0).doResume();
                }
            }
							
            $("#main-image #photo").hide();
            $("#VideoProducts").show();
            $("#MoreImages").hide();
        }
        else
        {
            $("#main-image #video").hide();
            // Stop the flash from playing (IE6 plays even after toggling)
            var obj = $("#main-image .flash-ready").children("object");
            if(obj != null && obj.size() > 0 && obj.get(0).doStop)
            {
                obj.get(0).doStop();
            }
						
            $("#main-image #photo").show();
            $("#VideoProducts").hide();
            $("#MoreImages").show();
        }

        $(selector).text(newText).attr('href','javascript:toggleVideo("'+currentText+'");');
    }
    else
    {
        //alert("no required version");
				
        // Needs flash (or a better version)
        generateGetFlashLink("#main-image");
        $("#video-link").empty().addClass("no-image");
        $("#main-image #video").hide();
    }
}

function changeBagItFormSubmit() 
{
    //alert('changeBagItFormSubmit: start' + $("form.PrdHndl").length);
    $("form.PrdHndl").attr("target", "prdpop");
    /* works without this
		$("#submit_btn").click(function() {
		  popup('/sc/servlet/PrdHndl','prdpop');
		});
		*/
    // FIXME: issue with Google Chrome and cleaning up of deleted dom elements
    $("#review-bag").attr("value", "nothing-to-see-here");
    $("#review-bag").remove();
}
	
function openSizing() 
{
    window.open('/static_pages/sizing.html', 'sizepop', config='height=500,width=535,toolbar=no,scrollbars=yes,resizable=yes,location=no,status=yes');
}	
