
// a placeholder for the currently selected tab
var currenttab = '';

// this function must now be in the global scope because it is accessed from the hometabs.html
function changeTabAndContents(tabid) {
    
    // if the same tab is already selected, do not proceed
    if (tabid == currenttab) {
        return;
    }
    
    // assign the current tab id to the id passed into the function
    currenttab = tabid;
    
    // giles 2 - reset the corners of the big transparent div
    $('div.bigtransparent').unkorner().korner();
    
    // giles 2 - the index of the first and last element
    var firstIndex = 0;
    var lastIndex = $('div.transparentbuttons').size() - 1;
    
    /*  giles 2 - 
        If the button is the one selected, remove rounded corners at the top, 
        increase its padding, decrease its margin. If it's the first element,
        remove the bottom left (bl) corner from the bigtransparent div, if 
        it's the last, remove the bottom right corner. 
        For all other elements, reset their rounding.
    */
    $('div.transparentbuttons').each(function(index,element) {
                    
        if (tabid == element.id) {
            
            $(element)
                .css('paddingTop', '10px')
                .css('marginTop', '0px')
                .unkorner()
                .korner("br bl");
            
            if (index == firstIndex) {
                $('div.bigtransparent').unkorner().korner("br tl tr");
            } else if (index == lastIndex) {
                $('div.bigtransparent').unkorner().korner("bl tl tr");
            }
            
        } else {
            
            $(element)
                .css('paddingTop', '0px')
                .css('marginTop', '10px')
                .unkorner()
                .korner();
        } 
    });
    
    // no longer storing the page contents in the hash, but in the html file (it was messing up the IE cornering)
    $('div.bigtransparent div.b-tab').hide();   // now hide all the b-tab content
    $('div.bigtransparent #b-' + tabid).show(); // and show the selected one
}



// when the document is loaded, jquery will call this function
$(function() {    
    
    
    
        
    
    // use the jQuery $.each() method to for-each through all the tabs, and set hover event handlers
    $('div.transparentbuttons').each(function(tab) {
        $(this).hover(function(event) {
            /*
                note the use of "this", and not "event.target.id", because children of the tab div (like 
                "<h1>") might trigger the event, and won't have the correct id 
            */
            changeTabAndContents(this.id);
        });
   });
    
    /*********************************************************************************************
    ****************************************** LE MENU *******************************************
    *********************************************************************************************/
    
    //$('div.content').show();
    
    /*
        GILES - Let's hide the contents until all the tab images are loaded.
    */
    (function() {
            
            var counter = 0
            var max = $('div.b-tab img').size();
            
            // only execute if we are on a page that has div.b-tab images
            if (max > 0) {
                
                function onComplete() {
                    counter++;
                    //console.log(counter);
                    if (counter >= max) {
                        $('div.content').show(); // all images have been loaded... let's show the page
                        //console.log("done");
                    }
                }
                
                $('div.content').hide();
                $('.b-tab img').each(function(n,image) {
                    if (image.complete) {
                        onComplete();
                    } else {
                        image.onload = onComplete;
                        //image.attachEvent("onload", onComplete );
                        
                        // you need to reassign the image src for IE9
                        // see http://nnucomputerwhiz.com/ie9-image-load-event-bug.html
                        image.src = image.src;
                        
                        //console.log("still loading " + image.src);
                    }
                });
                
                
            }
            
        })();
     /* GILES - this strange looking construction 
                    (function(){...})(); 
                is a javascript block - it prevents other functions from 
                accessing it (we only ever want to run this at page load).
                it also prevents its variables clashing with others in 
                the global scope.
                jQuery plugins (like corner and korner, use this appraoch) */
    
    
    /*
        GILES - Selectively hides tab and bigtransparent text, but still keeps the image on the page
    */
    function hideTabsButShowImage() {
        $('.bigtransparent').addClass("bigtransparent_withoutbackground");      // new class defined in style.css that sets the background image to none
        $('.transparentbuttons').hide();                                        // hide the buttons
        $('.bigtransparent div.bigtransparenttext').hide();                     // hide the text
        $('.bigtransparent').klear();

    }
    
    /*
        GILES - Restores the tabs and bigtransparent text 
              - does the opposite to hideTabsButShowImage()
    */
    function showTabs() {
        $('.bigtransparent').removeClass("bigtransparent_withoutbackground");
        $('.transparentbuttons').show();
        $('.bigtransparent div.bigtransparenttext').show();
        $('.bigtransparent').unklear();
    }
    
    /*
        This will hide all level2 menus, and show the child of the parentMenu if it is not null
    */
    function showMenu2(parentMenu) {
        $("div.menu2").hide();//.css("left", "-10000px");                // hide all level 2 menus
        if (parentMenu != null) {
            $('div.menu2', parentMenu).show();//.css("left" , "0px");    // display the child
        }
    }
	
	// GILES - not necessary
	// function showMenu4(parentMenu) {
	//         $("div.menu4").hide();//.css("left", "-10000px");                // hide all level 2 menus
	//         if (parentMenu != null) {
	//             $('div.menu4', parentMenu).show();//.css("left" , "0px");    // display the child
	//         }
	//     }
    
    /*
        This will hide all level3 menus, and show the child of the parentMenu if it is not null
    */
    function showMenu3(parentMenu) {
        $("div.menu3").hide();//.css("left", "-10000px");
        if (parentMenu != null) {
            $('div.menu3', parentMenu).show();//.css("left" , "0px");
            // as this 3rd level menu is ontop of the tab container, we hide the container
            // GILES - note the new function call
            hideTabsButShowImage();////$('div.content').hide();
        }
    }
    
    /* 
        Assign a mouseenter event handler for all level 1 menu items (to display level 2 menus).
    */
    $('div.menuitem').each(function(menuitem) {
       $(this).mouseenter(function(event) {
           showMenu2(this);
       });
    });
    
    /* 
        Assign a mouseenter event handler for all level 2 menu items (to display level 3 menus).
    */
    $('div.menuitem2').each(function(menuitem) {
       $(this).mouseenter(function(event) {
           showMenu3(this);
       });
    });
    
    /* 
        Assign a mouseleave event handler to reset the menus and, if hidden, to show the 
        tab container.
    */
    $('div.menucontainer').mouseleave(function(menucontainer) {
        showMenu2(null);
        showMenu3(null);
        // GILES - note the new way of hiding
        showTabs(); //$('div.content').show();
    });
    
    
    
    
    /***************************************************************************
        UHV COMPONENTS
    ****************************************************************************/
    
    if ($('.instrument_text_container').size() > 0) {
        
        $("html").css("overflow-y", "hidden");
        
        $("body").append("<div id='slider-vertical' style='position:absolute;right:10px;top:180px;'></div>");
        
        // use the jquery slider as a scrollbar
        $( "#slider-vertical" ).slider({
            orientation: "vertical",
            min: 0,
            max: 100,
            value: 100,
            slide: function( event, ui ) {
                $('.instrument_text_container').each(function(n,item) {
                    
                    // Very important! Attempting to adjust the non visible divs causes the whole technique to fail
                    if (! $(item).is(":visible"))
                        return;
                        
                    var max = $.scrollTo.max(item, "y");
                    var scrollTo =  ((100 - ui.value) / 100) * max ;

                    $(item).scrollTo(scrollTo, {axis : "y"});

                });
            }
        }).height(400);
        
        // capture mousewheel events to scroll, and to reset the scrollbar
        $(document).bind('mousewheel', function(event, delta) {
            $('.instrument_text_container').each(function(n,item) {
                
                // Also Very important! See above!
                if (! $(item).is(":visible"))
                    return;
                
                var scrollTo=0;
                delta = -delta; // need to flip
                var increment = 10;
                if (delta > 0) {
                    scrollTo = "+=" + parseInt(delta * increment) + "px";
                } else {
                    scrollTo = "-=" +  - parseInt(delta * increment) + "px";
                }
                
                $(item).scrollTo(scrollTo, {axis : "y"});
                
                var max = $.scrollTo.max(item, "y");
                var sliderPos = 100 - ($(item).scrollTop() / max * 100);
                
                $( "#slider-vertical" ).slider("option", "value", sliderPos);
                
            });
        });
        
        
        
        /*
            This checks to see if there is one or more instrument_text_container divs. If there are, it will attempt
            to catch window scroll events. Using the information from these events, it taps into the jquery.scrollTo
            plugin, and uses that to adjust the scroll position of those divs. 
        */
        /*
        function adjust() {
            
            var adjusted = false;
            
            while (! adjusted) {
                var winHeight = $(window).height();
                var docHeight = $(document).height();
                
                if (docHeight > winHeight) 
                     adjusted = true;
                
                $("body").append("<br>");
                
            }
            
            
        }
        
        setTimeout(adjust, 1000);
        
        $(window).scroll(function(e) {
            // e.preventDefault();
            // e.stopImmediatePropagation();
            
            var winHeight = $(window).height();
            var docHeight = $(document).height();
            
            var rangeHeight = docHeight - winHeight;
            
            
            var scrollPos = (document.documentElement.scrollTop ?
                        document.documentElement.scrollTop :
                        document.body.scrollTop);
                        
            var relScrollPos = scrollPos / rangeHeight;
            
            console.log(winHeight, docHeight, rangeHeight, scrollPos, relScrollPos);
            
            $('.instrument_text_container').each(function(n,item) {
                
                // Very important! Attempting to adjust the non visible divs causes the whole technique to fail
                if (! $(item).is(":visible"))
                    return;
                    
                    
                var max = $.scrollTo.max(item, "y");
                var scrollTo = relScrollPos * max;
                //console.log(relScrollPos, max, scrollTo);
                
                $(item).scrollTo(scrollTo, {axis : "y"});
                
            });
            
            // return false;
        });
        
        */
    }
    
    
    
    // @TODO - we should really be using removeClass() and addClass() rather than css() here
    function showComponentTab(title) {
        $(".instrument").hide();                                                   // hide all instrument divs
        $("#"+title.toLowerCase()).show();                                         // show the one that matches the title

        $('.instrument_text_links_container a').css('background-color', 'rgb(200,200,200)');    // reset all link styles
		var linkselector = 'a[title="' + title + '"]';                             // get the links that match the title
        $(linkselector).css('background-color', 'rgb(82,33,69)');                       // apply the desired style

        $('.instrument_thumb').css('backgroundColor', "#EBEBEB");                  
        var imageselector = 'a[alt="' + title + '"]';
        $(imageselector).parent().css('backgroundColor', "#BBB");                  // note here we apply the style to the parent
        
        // if the slider is present reset it
        $( "#slider-vertical" ).slider("option", "value", 100);
    }


    $('.instrument_text_links_container a').click(function(event) {
        var title = $(event.currentTarget).attr('title');
        showComponentTab(title);
    });

    $('.instrument_thumb_container a').click(function(event) {
        // alt is an img tag attribute, so you should really use a title like above (in my previous comment I assumed you were going to put the click handler on the img)
        var alt = $(event.currentTarget).attr('alt');
        showComponentTab(alt);
    });

	$(".instrument_thumb1").hover(function(e) {
        $(this).css("backgroundColor", "rgb(200,200,200)");
    }, function(e) {
        $(this).css("backgroundColor", "rgb(235,235,235)");
    });

    // show the first tab by default
    showComponentTab("Overview");
    
    
    

});






    
    
/*********************************************************************************************
    Global Contacts
**********************************************************************************************/

/*
    This hash of hashes contains the global contact data. Edit this to add new contacts.
*/
var addresses = {
    "mantis" : {
        "title" : "Mantis Deposition Ltd",
        "countries" : ["United Kingdom"],
        "address" : ["2 Goodson Industrial Mews","Wellington Street","Thame","Oxfordshire OX9 3BX","UK"],
        "latlng" : [51.745984,-0.973643],
        "tel" : "+44 1844 260160",
        "fax" : "+44 1844 260421",
        "email" : "sales@mantisdeposition.com",
        "www" : "www.mantisdeposition.com"
    },
	 "mantisus" : {
        "title" : "Mantis Deposition Inc - USA",
        "contact" : "Brandon Brandt",
        "countries" : ["USA, Canada and Mexico"],
        "address" : ["1173 Havenview Drive","Shakopee, MN 55379","USA"],
        "latlng" : [44.772475, -93.510091],
        "tel" : "+1 763 370 7304",
        "fax": "+1 888 370 4791",
        "email" : "brandon.brandt@mantisdeposition.com",
        "www" : "www.mantisdeposition.com"
    },
    
    "mantisfrance" : {
        "title" : "Nanoandmore France",
        "contact" : "Gilbert Gillman",
        "countries" : ["France"],
        "address" : ["33 rue Vital", "75016 Paris", "France"],
        "latlng" : [48.858835, 2.278113],
        "tel" : "+33 01 428 829 67",
        "fax" : "+33 01 428 832 07",
        "email" : "sales@nanoandmore.fr",
        "www" : "www.nanoandmore.fr"
    },
	
	"mantisgreece" : {
        "title" : "ITC",
        "contact" : "Simeon Argyropoulos",
        "countries" : ["Greece"],
        "address" : ["22 Filellinon Street", "GR-546 45 Thessaloniki", "Greece"],
        "latlng" : [40.600781, 22.956086],
        "tel" : "+30 231 085 6585",
        "fax" : "+30 231 043 5868",
        "email" : "sargyitc@otenet.gr"
    },
	"mantislatvia" : {
        "title" : "SIA Saint-Tech",
        "contact" : "Vadim Shakel",
        "countries" : ["Latvia"],
        "address" : ["Maskava Street 418-4", "Riga", "Latvia"],
        "latlng" : [56.946536, 24.10485],
        "tel" : "+371 671 32303",
        "cell" : "+371 297 06045",
        "email" : "info@saint-tech.lv",
        "www" : "www.saint-tech.lv"
    },
    "mantisspain" : {
        "title" : "Avactec",
        "contact" : "Tim Doust",
        "countries" : ["Spain and Portugal"],
        "address" : ["Calle de Enrique Granados, 49", "28660 Boadille del Monte", "Madrid", "Spain"],
        "latlng" : [40.4028, -3.888643],
        "tel" : "+34 918 286 158",
		"fax" : "+34 916 321 929",
        "email" : "info@avactec.es",
        "www" : "www.avactec.es"
    },
	"mantisscandinavia":{
		"title" : "ROWACO AB",
		"contact" : "Kristian Flodstr&#246;m",
		"countries" : ["Sweden, Denmark, Finland and Norway"],
		"address" : ["Westmansgatan 49", "S-582 16 Linkoping", "Sweden"],
		"latlng" : [58.404055, 15.603404],
		"tel" : "+46 (0)13 138 010",
		"fax" : "+46 (0)13 311 335",
		"email" : "kristian@rowaco.se",
		"www" : "www.rowaco.se"
	},
    "mantisrussia" : {
        "title" : "ARUAL-Tech Co. Ltd.",
        "countries" : ["Russia"],
        "address" : ["2-3, Mezhevoy ch. str.", "St. Petersburg", "Russia 198035"],
        "latlng" : [59.911024, 30.252828],
        "tel" : "+7 (906) 251 8400",
        "fax" : "+7 (812) 513 3351",
        "email" : "info@arualtech.ru",
        "www" : "www.arualtech.ru"
    },
    "mantischina" : {
        "title" : "Cross-tech Development Co. Ltd.",
        "contact" : "Nick Zhang",
        "countries" : ["China"],
        "address" : ["Suite 902, No.3, Magnolia Green Square, Lane 251", "<br>SongHuaJiang Road", "Shanghai", "China","200093"],
        "latlng" : [31.284701,121.536355],
        "tel" : "+86 215 603 5615",
        "cell" : "13916855175",
        "fax" : "+86 216 630 3256",
        "email" : "info@cross-tech.com.cn",
        "www" : "www.cross-tech.com.cn"
    },
    "mantissouthkorea" : {
        "title" : "NanoPascal Korea Corp",
        "contact" : "Kevin Cho",
        "countries" : ["South Korea"],
        "address" : ["Rm. 614, Sungjee Heightstel", "245-3 Seohyun-Dong", "Bundang-gu", "Sungnam-City",
        "<br>Kyonggi-do","463-824", "Korea"],
        "latlng" : [37.38562, 127.122509],
        "tel" : "+82 317 075 080",
        "cell" : "+82 183 945 375",
        "fax" : "+82 317 073 618",
        "email" : "nanopascal@korea.com",
        "www" : "www.nanopascal.com"
    },
    "mantisjapan" : {
        "title" : "TEGA Science,Inc.",
        "contact" : "Shuichi Yoshida",
        "countries" : ["Japan"],
        "address" : ["3-5-4 Kita-Kashiwa", "Kashiwa", "Chiba", "Japan 277-0832"],
        "latlng" : [35.871576, 139.987355],
        "tel" : "+81 471 685 311",
        "fax" : "+81 471 685 671",
        "email" : "shuichi@tegascience.co.jp",
        "www" : "www.tegascience.co.jp"
    },
    "mantistaiwan" : {
        "title" : "Advantage Scientific, Inc.",
        "contact" : "Adam Yang",
        "countries" : ["Taiwan"],
        "address" : ["11F-6, No. 268 Liancheng Road", "Junghe City", "Taipei Hsien", "Taiwan 235"],
        "latlng" : [24.994446, 121.497029],
        "tel" : "+886 282 273 000",
        "cell" : "+866 921 104 000",
        "email" : "adienyang@seed.net.tw",
        "www" : "www.advantage.com.tw"
    },
    "mantissingapore" : {
        "title" : "Research Instruments Pte Ltd",
        "contact" : "Graham Bennett",
        "countries" : ["Singapore"],
        "address" : ["26 Ayer Rajah Crescent", "#03-10 Singapore 139944"],
        "latlng" : [1.29618, 103.7912],
        "tel" : "+65 657 108 88",
        "cell" : "+65 938 214 01",
        "fax" : "+65 657 108 68",
        "email" : "graham@ri.com.sg",
        "www" : "www.ri.com.sg"
    },
    "mantisindia" : {
        "title" : "SG Instruments PVT Ltd",
        "contact" : "Sandipan Guha",
        "countries" : ["India"],
        "address" : ["B-9, M-4, Gupta Plaza", "Vikas Puri New Delhi - 110018", "India"],
        "latlng" : [28.635308, 77.22496],
        "tel" : "+91 114 288 3851",
        "fax" : "+91 112 555 6527",
        "email" : "gsandipan@sg-instruments.com",
        "www" : "www.sg-instruments.com"
    },
    "mantisemirates" : {
        "title" : "SANCO (ME) FZC",
        "contact" : "Ahtisham Ulhaq",
        "countries" : ["United Arab Emirates and Saudi Arabia"],
        "address" : ["P.O.Box 8447, Sharjah", "United Arab Emirates"],
        "latlng" : [25.366667, 55.383333],
        "tel" : "+971 655 715 47",
        "fax" : "+971 655 715 49",
        "email" : "ahtisham@sanco-me.com",
        "www" : "www.sanco-me.com"
    }
    
};

/*
    This will be called when a user clicks on a global contact, and also once when global contacts the page loads up.
*/
function showAddress(contactid) {
    
    // deselect all the contacts, then select the one that was clicked on
    $("div.contact_country a").removeClass("selected");
    $("#" + contactid).addClass("selected");
    
    // grab the relevant contact hash from the addresses hash
    var contact = addresses[contactid];
    
    // only draw maps if we have an address
    if (contact.latlng != null) {
        
        $('#map_canvas').show();
        
        var latlng = new google.maps.LatLng(contact.latlng[0],contact.latlng[1]);
        var myOptions = {
          zoom: 14,
          center: latlng,
          iwloc:"M",
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var map = new google.maps.Map(document.getElementById("map_canvas"),
               myOptions);

        var marker = new google.maps.Marker({
             position: latlng,
             title:contact.title
         });

        marker.setMap(map);
        
        
        
    } else {
        
        // hide the map canvas otherwise
        $('#map_canvas').hide();
    }
    
    // clear all contact info
    $(".contact_info").html("");
    
    // populate the relevant contact information, except for the title, check first 
    // to see if the information is in the hash
    
    $("#contract_address_title").html(contact.title);
    
    if (contact.address != null) {
        $("#contract_address_address").html(contact.address.join(", "));
    }
    
    if (contact.contact != null) {
        $("#contract_address_contact").html("<i>contact</i> " + contact.contact);
    }
    
    if (contact.tel != null) {
        $("#contract_address_tel").html("<i>tel</i> " + contact.tel);
    }
    
    if (contact.cell != null) {
        $("#contract_address_cell").html("<i>cell</i> " + contact.cell);
    }
    
    if (contact.fax != null) {
        $("#contract_address_fax").html("<i>fax</i> " + contact.fax);
    } 
    
    if (contact.email != null) {
        $("#contract_address_email").html("<a href='mailto:"+contact.email+"'>" + contact.email + "</a>");
    }
    
    if (contact.www != null) {
        $("#contract_address_www").html("<a href='http://"+contact.www+"'>"+contact.www+"</a>");
    }
    
}

function initAddresses() {
    
    // round the contacts div
    $('div.contacts').korner();
    
    // generate the clickable list of contacts from the addresses hash
    for(var addressKey in addresses) {
        var address = addresses[addressKey];
        var countries = address.countries.join(", ");
        $("#contact_list").append("<div class='contact_country' ><a id='"+ addressKey +"' >" + countries + "</a></div>")
    }
    
    $(".contact_country").click(function(event) {
        showAddress(event.target.id);
    });
    
    // start the page with mantis as default
    showAddress("mantis");
    
}

