/** 
 * Various Javascript functions used throughout the website
*/

// The only way currently to get the screen resolution in PHP is to do it via Javascript
// Since we need that bit of information on every page, we need to run it outside of a function
checkScreenCookie();

// The function for the above call
function checkScreenCookie(){
    
    // Even if we have a valid cookie, the user may have changed the resolution
    var cookieValue = screen.width;
    var cookieName = "clientScreen" + cookieValue;
    var overrideCookie = false;
    
    // Determine todays date and add a week
    var currentDate = new Date();
    var currentTime = currentDate.getTime()+(7*24*60*60*1000);
    
    // Time is in milliseconds, so we do *1000 to seconds, *60 to minutes, *60 to hours and *24 to days
    currentDate.setTime(currentTime);
    
    // So we need to check it to see if they match, we also check if it even exists
    if(readCookie("clientScreen") != cookieValue && readCookie("clientScreen") != ""){

        // Allow for an override even if the cookie exists
        overrideCookie = true;
    }
    
    // See if the cookie exists
    if(readCookie("clientScreen") == "" || overrideCookie == true){
        
        // set the expire
        var expires = "; expires="+currentDate.toGMTString();
        
        // Set the cookie
        document.cookie = cookieName + expires + "; path=/";
        
        // Reload the page, but make sure the cookie we made is valid so we don't loop
        if(readCookie("clientScreen") == cookieValue){
            
            // do the reload
            document.location.reload();
        }
    }
}

// This function reads in a cookie, doesn't matter if multiple are found
function readCookie(name) {
    
    // first, we need to set the name to search for, we add an =
    var cookieName = name + "=";
    var returnValue = "";
    
    // create a separate key for each cookie in an array
    var cookieArray = document.cookie.split('; ');
    
    // loop through the array
    for(var i = 0; i < cookieArray.length; ++i) {
        
        // set the current cookie in a variable
        var currentCookie = cookieArray[i];
        
        // if we have a match, we found our precious cookie
        if(currentCookie.indexOf(cookieName) == 0){
            
            // update the return value with the result
            returnValue = currentCookie.substring(cookieName.length,currentCookie.length);
        }
    }
    
    // return the result
    return returnValue;
}

// Next up, keeping the background image nicely sized without streching it to one side or the other
window.onresize = backgroundUpdate;

function backgroundUpdate(){
    
    // get the image containing the background
    var theImg = document.getElementById('bgImg');
    
    // hide the image so it can be modified (needed for IE)
    document.getElementById('bgImg').style.display = "none";
    var pageWidth = document.body.offsetWidth;
    var pageHeight = document.body.offsetHeight;
    var newWidth = 0;
    var newHeight = 0;
    
    // base is always 1
    var modifier = 1;
    
    // modify depend on what is higher
    if(pageWidth >= pageHeight){
        
        modifier = pageWidth / theImg.width;
        
    }else{
        
        modifier = pageHeight / theImg.height;
    }
    
    // IE thingy, loads with 0 width and height on page load for some reason
    if(navigator.appName == "Microsoft Internet Explorer" && theImg.width == 0){
        
        // load it manually
        var imgWidth = 1300;
        var imgHeight = 1050;
        
        // modify depend on what is higher
        if(pageWidth >= pageHeight){
            
            modifier = pageWidth / imgWidth;
            
        }else{
            
            modifier = pageHeight / imgHeight;
        }
        
        // Update the new sizes
        newWidth = imgWidth * modifier;
        newHeight = imgHeight * modifier;
        
    }else{
        
        // Update the new sizes
        newWidth = theImg.width * modifier;
        newHeight = theImg.height * modifier;
    }
    
    // make sure it ain't smaller in height then the window its in
    if(newHeight < pageHeight){
    
        newWidth *= (pageHeight / newHeight);
        newHeight *= (pageHeight / newHeight);
    }
    
    // do the modification
    document.getElementById('bgImg').width = newWidth;
    document.getElementById('bgImg').height = newHeight;
    document.getElementById('bgImg').style.display = "";

}

// Simplied getElementById
function getItem(id){
    
    // Get element
    var theItem = document.getElementById(id);
    
    // return the element
    return theItem;
}

// Close main window
function closeMain(overrideName, overrideNameBG){
    
    // Check
    var itemName = "mainPage";
    var itemNameBG = "mainPageBG";
    
    if(overrideName != undefined)
    {
        // Set it
        itemName = overrideName;
    }
    
    if(overrideNameBG != undefined)
    {
        // Set it
        itemNameBG = overrideNameBG;
    }
    
    // Set display to none
    getItem(itemName).style.display = "none"; 
    getItem(itemNameBG).style.display = "none";
}

// Close main & center
function closeMainCenter()
{
    // First close main
    closeMain();
    
    // Then close center
    getItem('centerPage').style.display = "none";
    getItem('centerPageBG').style.display = "none";
}

// Gets data for contact form mail
function sendContactForm(mailPage,warningMsg){
    
    // These fields MUST NOT be empty
    var fieldList = new Array("last_name", "email", "message");
    var passed = true;
    
    // Loop through the list
    for(var i = 0; i < fieldList.length; ++i){
        
        // Field item
        var fieldName = fieldList[i];
            
        // Add it
        if(getItem(fieldName).value == "" || getItem(fieldName).value == " " || getItem(fieldName).value == "  ")
        {
            passed = false;
        }
    }
    
    // Send the mail
    if(passed == true)
    {
        getItem("theForm").action = mailPage;
        getItem("theForm").submit();
        
    }else
    {
        alert(warningMsg);
    }
}

// Load up google maps
function gMapLoad(fromAddress, fromCity){
    
    // Variables
    var gMap;
    var gDirections;
    
    // Display hidden main page
    getItem("mainPageBG").style.display = "";
    getItem("mainPage").style.display = "";
    
    // Load the map and directions from divs
    gMap = new GMap2(getItem("mainContentPadding"));
    gMap.setCenter(new GLatLng(52.058662,4.505918), 15);
    
    // Now directions
    gDirections = new GDirections(gMap, getItem("centerContentPadding"));
    gDirections.load("from: " + fromAddress + ", " + fromCity + " to: Croesinckplein 24, 2722, Zoetermeer");
}

// Sends the job search form with the ID and keeps the search data with us
function sendSearchForm(urlDesc, menuType, lang, dir, name){
    
    // Get form
    var theForm = getItem("searchDataForm");
    
    // Set form action
    theForm.action = dir + lang + "/" + menuType + "/" + name + "/" + urlDesc + ".html";
    
    // Send form
    theForm.submit();
}

// Ensures a field only has numeric values
function checkNumeric(theField)
{
    // check the value before we do anything with it
    if(theField.value.length > 0){
        
        // get values
        var fieldValue = theField.value;
        var fieldLength = fieldValue.length;
        
        // loop through each character and see if its 0-9
        for(i = 0;  i < fieldLength;  ++i){
            
            // get the characters
            var theChar = fieldValue.charAt(i);
            
            // and see if they are numeric
            if(isNaN(theChar) == true){
                
                theField.value = "";
                break;
            }
        }
    }
}

// Source selection
function checkSourceSelection(theDropdown)
{
    // Check (last selection = show the extra field)
    if(theDropdown.options[theDropdown.selectedIndex].value == 6)
    {
        // Show the hidden row
        getItem("app_source_extra_row").style.display = "";
        
    }else{
        
        // Show the hidden row
        getItem("app_source_extra_row").style.display = "none";
        getItem("app_source_extra").value = "";
    }
}

// Check app form
function checkAppForm(sendPage, warningMsg){
    
    // Check fields
    var fieldList = new Array("app_surname", "app_email", "app_motivation");
    var passed = true;
    
    // Loop through the list
    for(var i = 0; i < fieldList.length; ++i){
        
        // Field item
        var fieldName = fieldList[i];
            
        // Add it
        if(getItem(fieldName).value == "" || getItem(fieldName).value == " " || getItem(fieldName).value == "  ")
        {
            passed = false;
        }
    }
    
    // Send the mail
    if(passed == true)
    {
        getItem("theForm").action = sendPage;
        getItem("theForm").submit();
        
    }else
    {
        alert(warningMsg);
    }
}

// Checks to see if the user should be redirected to the low-res site
function runResolutionCheck(){
    
    // True means we stay, false means we popup the user
    var resFine = true;
    
    // First, check to see if the user is using Mozilla 1.x or IE 6.x
    if(navigator.appName == "Microsoft Internet Explorer"){
        
        // Check the version
        if(/MSIE (\d+\.\d+);/.test(navigator.userAgent)){
            
            // Get the number
            var IEVersion = new Number(RegExp.$1);
            
            // Check it
            if(IEVersion <= 6){
                
                // Uh-oh
                resFine = false;
            }
        }
    }
    
    // Same check with Firefox, at the time of writing I'll assume FF 2 runs the site fine
    if(navigator.userAgent.indexOf("Firefox") >= 0){
        
        // Check the version
        if(/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent)){ 
            
            // Set it
            var FFVersion = new Number(RegExp.$1);
            
            // Check
            if(FFVersion <= 1){
                
                // Uh-oh
                resFine = false;
            }
        }
    }
    
    // Another attribute we check is screen size, as tiny resolutions cause issues
    if(screen.width <= 800 || screen.height <= 600 && screen.width <= 800){
        
        // Also, not good
        resFine = false;
    }
    
    // Return result
    return resFine;
}