﻿/// <reference path="jquery-1.3.2-vsdoc2.js" />

var pageTracker; //reference for Google Analytics tracking.
var Duroc = {};

(function($) {
    Duroc.DropDownLinks = {
        init: function() {
            $('#link-selector').change(function() {
                var url = $("option:selected", this).val();
                if (url != '') {
                    var newwindow = window.open(url);
                }
            });
        }
    };

    Duroc.ExpandableTable = {
        table: null,
        init: function() {
            this.table = $('.exp-table');
            this.setBehavior();
        },
        setBehavior: function() {
            $(this.table).find('a.toggle').click(function(e) {
                e.preventDefault();
                var thisRow = $(this).parent().parent();
                if ($(thisRow).hasClass('open')) {
                    $(thisRow).removeClass('open');
                    $(thisRow).addClass('closed');
                    $(thisRow).next('tr.content').addClass('hidden');
                }
                else if ($(thisRow).hasClass('closed')) {
                    $(thisRow).removeClass('closed');
                    $(thisRow).addClass('open');
                    var newRow = $(thisRow).next();
                    $(newRow).removeClass('hidden');
                }
                else {
                    $(thisRow).after('<tr class="content"><td colspan="2">loading</td></tr>');
                    var item = this;
                    $.ajax({
                        type: "POST",
                        url: "/webservices/AjaxService.asmx/GetSupplier",
                        data: "{'pageid':'" + $(this).attr('rel') + "'}",
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        processData: false,
                        cache: false,
                        success: function(msg, status) {
                            // Replace the div's content with the page method's return.
                            //                    $("").html(msg.d);
                            $(thisRow).addClass('open');
                            var newCell = $(thisRow).next().find('td');
                            $(newCell).html(msg.d);
                        },
                        error: function(xhr, msg, e) {
                            alert(msg + ', ' + e); //Error Callback
                        }
                    });
                }
            });
        }
    };

    $(document).ready(function() {
        Duroc.DropDownLinks.init();
        Duroc.ExpandableTable.init();
        $("#header .duroc-link").append("<em></em>");

        (function(){
			var slideshowItems = $("ul.startpage-slideshow-top");
			
			if(slideshowItems.length > 1){
				slideshowItems.ticker({});
			}
		})();

        $('.duroc-link').hoverIntent({
            sensitivity: 1,
            interval: 0,
            timeout: 500,
            over: function() {
                $('.duroc-link em').addClass('open'); $('.duroc-link em').animate({ top: "5" }, "fast");
                var hoverText = $(this).find('.stamp').attr("title");
                $(".duroc-link em").text(hoverText);
            },
            out: function() { $('.duroc-link em').animate({ top: "-60" }, "fast", null, function() { $('.duroc-link em').removeClass('open'); }); $('.duroc-link em').removeClass('expanded'); }
        });

        // Tabs
        $('#tabs').tabs();
        $("a.fancy-video").each(function() {
            var rel = $(this).attr('rel');
            $(this).fancybox({
                content: '<object width="425" height="355"><param name="movie" value="' + rel + '"></param>' +
                        '<param name="allowFullScreen" value="true"></param><param name="allowScriptAccess" value="always"></param>' +
                        '<embed src="' + rel + '" type="application/x-shockwave-flash" allowscriptaccess="always" width="425" height="355" allowfullscreen="true"></embed>' +
                        '</object>'
            });
            if ($(this).find("span.play")) {
                var image = $(this).find("img");
                var height = $(image).height();
                var width = $(image).width();
                var posx = Math.floor((width - 41) / 2);
                var posy = Math.floor((height - 41) / 2);
                var playbutton = $(this).find("span.play");
                jQuery(playbutton).css("top", posy + "px").css("left", posx + "px");
            }
        });

        $("a.fancy").fancybox({
            'titleShow': false,
            'transitionIn': 'elastic',
            'transitionOut': 'elastic'
        });  

        $("a.email-a-friend").fancybox({
			type:'iframe',
			width:476,
			height:600
        });  
		
		$("#right-content ul.share-this li a").each(function(){
			var link = $(this);
			
			link.attr("title", link.text());
		});
		
		$("#news-list-with-dropdown").each(function(){
			var list = $(this);
			
			var url = location.href;
			var queryStringValues = {};
			function parseQueryString(queryString){
				var values = {};
				
				$.each(queryString.split("&"), function(index, keyValuePair){
					var parsedKeyValuePair = keyValuePair.split("=");
					
					var key = parsedKeyValuePair[0];
					var value = parsedKeyValuePair[1];
					
					values[key] = value;
				});
				
				return values;
			}
			if(url.indexOf("?") != -1){
				var queryString = url.substr(url.indexOf("?") + 1);
				
				queryStringValues = parseQueryString(queryString);
				
				url = url.substr(0, url.indexOf("?"));
			}
			
			var dropdown = $("<select></select>").attr("id", "news-list-dropdown");
			
			$.each(window.years, function(key, value){
				var option = $("<option></option>").text(value);
				
				if(queryStringValues.year == value){
					option.attr("selected", true);
				}
				
				dropdown.append(option);
			});
			
			dropdown.change(function(){
				queryStringValues.year = dropdown.val();
				
				function getQueryString(values){
					var queryString = "";
					
					var valueList = [];
					
					$.each(values, function(key, value){
						valueList.push(key + "=" + value);
					});
					
					return valueList.join("&");
				}
				
				var queryString = getQueryString(queryStringValues);
				
				location.href = url + "?" + queryString;
			});
			
			var dropdownWrapper = $("<div></div>").addClass("news-list-dropdown-wrapper").insertBefore(list);
			
			dropdown.appendTo(dropdownWrapper);
			
			$("<label></label>").text(window.yearLabel).attr("for", "news-list-dropdown").appendTo(dropdownWrapper);

		});

        
        //Duroc Machine Tool megadropdown productcatalog
        $("#main-menu ul li").hoverIntent({ over: function () {
            var div = $(this).find("div"); if (div.length > 0) {
                if ($.browser.msie && parseFloat($.browser.version) < 7)
                    $("select").css({ 'visibility': 'hidden' }); $(div).css({ 'opacity': '1' }); 
                    if (!$.support.opacity)
                    {
                        $(div).get(0).style.removeAttribute('filter'); 
                    }
                    $(div).css({ 'top': '31px' }).css({ 'display': 'inline-block' });

                    $("#main-menu ul li div.dropdown:eq(0)").css({'left' : '0px'});
                    $("#main-menu ul li div.dropdown:eq(1)").css({'left' : '-114px'});
                    $("#main-menu ul li div.dropdown:eq(2)").css({'left' : '-383px'});


                    //set li to selected upon hover:
                    $(this).addClass('hover');
            }
        }, out: function () {
            var div = $(this).find("div"); if (div.length > 0) {
                if ($.browser.msie && parseFloat($.browser.version) < 7)
                    $("select").css({ 'visibility': 'visible' }); 
                    if ($.support.opacity)
                    {
                        $(div).animate({ 'opacity': '0' }, 200, function () { $(this).css({ 'display': 'none' }) }); 
                    }
                    else
                    $(div).css({ 'display': 'none' });

                //set li to selected upon hover:
                $(this).removeClass('hover');
            }
        }
        });


        //Makes a 2 column layout out of brands in the first dropdownmenu       
        //only first dropdownmenu $('#main-menu .dropdown .dd-brands ul:eq(0)').easyListSplitter({ colNumber: 2 });
        $('#main-menu .dropdown .dd-brands ul').easyListSplitter({ colNumber: 2 });


    });//end of document ready
	
	// $(window) onload waits until all images have been loaded, as opposed to $(document) onLoad.
	$(window).load(function(){
		initStartpageBrandSlideshow();
	});
	
	function initStartpageBrandSlideshow(){
		var slideshow = $("ul.startpage-brands-slideshow");
		
		if(slideshow.length == 0){
			return;
		}
		
		slideshow.jcarousel({
			visible:3,
			scroll:2,
			start:Math.floor(Math.random() * slideshow.children().length + 1),
			wrap:"circular"
		});
		
		var items = slideshow.children();
		
		var maxHeight = 0;
		
		items.each(function(){
			maxHeight = Math.max($(this).height(), maxHeight);
		});
		
		items.each(function(){
			var item = $(this);
			var itemHeight = item.height();
			var rest = maxHeight - itemHeight;
			
			item.css("padding", Math.floor(rest/2) + "px" + " " + "0");
		});
	}
})(jQuery);
