/*
* Auto-executing function
*/
var date = new Date();
var variables = getUrlVars();

var defaultHost = document.getElementById('hdnDefaultHost').value;
var mobileHost = document.getElementById('hdnMobileHost').value;
var hostName = document.location.hostname;
var timeToDetectSlowConnection = document.getElementById('hdntTimeToDetectSlowConnection').value;
var RedirectPagePath = document.getElementById('hdnRedirectPagePath').value;
var ignoreSlowConnection = document.getElementById('hdnIgnoreSlowConnection').value;
var isSlowConnection = true;
var enableMobileVersion = document.getElementById('hdnEnableMobileVersion').value;

/* JUST FOR CDR TESTING IE6 */
if (hostName === '81.180.150.125') {
    hostName = window.location.host;
}

/* set submit value on forms */
var submitLabel = $("#hdnSubmitLabel").val();
$(".contourNavigation input").val(submitLabel);

//detect slow connection
if ((Number(timeToDetectSlowConnection)).toString() == 'NaN') {
    timeToDetectSlowConnection = 5;
}
timeToDetectSlowConnection *= 1000;
function slowConnectionNotification() {
    if (isSlowConnection) {
        window.location = RedirectPagePath;
    }
}

// This function is used on body onload event. The slow connection notification is canceled on body onload. So if the page took less than x
// secs to load the message will not appear.
function cancelSlowConnection() {
    setTimeout("isSlowConnection = false;", 1);
    //isSlowConnection = false;
}
// if the page will take more than 'timeToDetectSlowConnection' seconds to load, notify user for slow connection
if (hostName == defaultHost && window.location != RedirectPagePath && ignoreSlowConnection != 'true') {
    setTimeout("slowConnectionNotification();", timeToDetectSlowConnection);
}

if (hostName == defaultHost && ignoreSlowConnection != 'false') {    
    jQuery(document).ready(function() {
        //detect mobile connection
        if (mobileHost != '' && mobileHost != undefined) {
            if (screen.width < 600 && hostName != mobileHost && enableMobileVersion == '1') {
                window.location = "http://" + mobileHost;
            }
        }

        /*
        var timer = setInterval(function () {
        if (typeof jQuery === 'function' && jQuery('html').hasClass('ie6')) {

         //jQuery.getScript("/scripts/ie6_scripts.js", function() {
        //jQuery('#main_menu_ul li:first-child').css({
        //zIndex: 2
        //});
        //jQuery('#main_menu_ul > li').find('ul').show().hide();
        //});
        clearInterval(timer);
        } else if (typeof jQuery === 'function' && !jQuery('html').hasClass('ie6')) {
        clearInterval(timer);
        }
        }, 10);
        */

        var showLessText = (document.getElementById('hdnShowLess') == null) ? "show less" : document.getElementById('hdnShowLess').value;
        var showMoreText = (document.getElementById('hdnShowMore') == null) ? "show more" : document.getElementById('hdnShowMore').value;
        jQuery('.expanding_text').expander({
            slicePoint: 350,  // default is 100
            expandPrefix: '',
            expandSpeed: 100,
            expandText: showMoreText, // default is 'read more...'
            userCollapseText: showLessText,  // default is '[collapse expanded text]'
            beforeExpand: function($thisEl) {
                if (typeof jQuery($thisEl).data('firstLoad') === 'undefined') {
                    jQuery($thisEl).parent().css({
                        height: 'auto',
                        overflow: 'visible'
                    });
                    jQuery($thisEl).data('firstLoad', 1);
                }

                jQuery($thisEl).find('.details').data('active', 1);
                jQuery('.details').each(function() {
                    if (jQuery(this).data('active') !== 1) {
                        jQuery(this).hide().prev('span.read-more').show();
                    } else {
                        jQuery($thisEl).find('.details').data('active', 0);
                    }
                });
            },
            afterExpand: function($thisEl) {
                jQuery('#page_left_menu, #main_content').equalHeightCustom(true);
            },
            onCollapse: function($thisEl) {
                jQuery('#page_left_menu, #main_content').equalHeightCustom(true);
            }
        });

        var tabsLoaded = false;
        jQuery("#tabs").tabs({
            show: function() {
                if (tabsLoaded) {
                    jQuery('#page_left_menu, #main_content').equalHeightCustom(true);
                } else {
                    tabsLoaded = true;
                }
            }
        }).show();
        jQuery('#page_left_menu, #main_content').equalHeight(false, ((jQuery('#calendar_menu')) ? jQuery('#calendar_menu').find('ul:first').height() : 0) + parseInt(jQuery('#page_left_menu').css('marginTop'), 10));

       /*if (jQuery('marquee').size() > 0) {
			jQuery('marquee').marquee('pointer');
            jQuery('.pointer').css({
                position: 'absolute'
            });
            jQuery('.pointer span').css({
                position: 'absolute',
                width: 2 * (jQuery('.pointer span').width() - 82)
            });
        }*/
		
		
		if (jQuery('marquee').size() > 0) {
			jQuery('.site_info_logo_text').each(function() {
				jQuery('marquee').marquee('pointer');
				jQuery('.pointer').css({
					position: 'absolute'
				});
				if(jQuery(this).find('.pointer').find('span').width() > jQuery(this).find('.pointer').width()){
					var widthm = 2 * jQuery(this).find('.pointer').find('span').width()
				}else{
					var widthm = (2 * jQuery(this).find('.pointer').find('span').width()) - jQuery(this).find('.pointer').find('span').width()
				}

				jQuery(this).find('.pointer').find('span').css({
					position: 'absolute',
					width:widthm
				});
			})
        }
		
		jQuery('.sltable tr:odd').addClass("odd");
        jQuery('.news_item_container .news_item h1').equalHeight();
        jQuery('.news_item_container').equalHeight();
        jQuery('#site_info_logo, .site_info_logo_container').equalHeight();

        /*
        * Image banner
        * Speed and timeout are set in hidden input fields
        * If input fields are empty fallback to default values
        */
		
	
        var slideshow_speed = 1000;
        var slideshow_time = jQuery('#slideshow_time').val();
        //slideshow_speed = (slideshow_speed != '') ? slideshow_speed : 200;
        slideshow_time = (slideshow_time != '') ? slideshow_time : 3000;

        jQuery('.slideshow').cycle({
            fx: 'fade',
            speed: slideshow_speed,
            timeout: slideshow_time
        });

        var day = (variables['day']) ? variables['day'] : date.getDate(),
                month = (variables['month']) ? variables['month'] - 1 : date.getMonth(),
                year = (variables['year']) ? variables['year'] : date.getFullYear();
        date = new Date(year, month, day);

        var isCalendarFirstLoaded = 1;
        jQuery("#calendar").datepicker({
            onChangeMonthYear: function(year, month, inst) {
                if (isCalendarFirstLoaded === 0) {
                    window.location = getUrl(document.location.pathname, variables['category'], year, month, '1', 'month');
                }
            },
            onSelect: function(date) {
                var selectedDate = new Date(date);
                window.location = getUrl(document.location.pathname, variables['category'], selectedDate.getFullYear(), parseInt(selectedDate.getMonth() + 1), selectedDate.getDate(), 'day');
            }
        });
        jQuery("#calendar").datepicker("setDate", date);
        isCalendarFirstLoaded = 0;
    });
}

function getUrl(path, category, year, month, day, mode) {
    if (category != "" && category != undefined) {
        path += "?category=" + category;
    }
    if (year != "" && year != undefined) {
        path += (path.indexOf("?") != -1 ? "&" : "?") + "year=" + year;
    }
    if (month != "" && month != undefined) {
        path += (path.indexOf("?") != -1 ? "&" : "?") + "month=" + month;
    }
    if (day != "" && day != undefined) {
        path += (path.indexOf("?") != -1 ? "&" : "?") + "day=" + day;
    }
    if (mode != "" && mode != undefined) {
        path += (path.indexOf("?") != -1 ? "&" : "?") + "mode=" + mode;
    }
    return path;
}


// Read a page's GET URL variables and return them as an associative array.
function getUrlVars() {
    var vars = [], hash;
    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 validatePhoneNumber(input) {
    if (input.length == 0) {
        return false;
    }
    var ValidChars = "0123456789+ ";
    var valid = true;
    var Char;
    for (var i = 0; i < input.length && valid; i++) {
        Char = input.charAt(i);
        if (ValidChars.indexOf(Char) == -1) {
            valid = false;
        }
    }
    return valid;
}

function validateEmail(email) {
    var emailFilter = /^[^@]+@[^@.]+\.[^@]*\w\w$/;
    return (emailFilter.test(email))
}


function GoogleSearchPage(path) {

    var searchValue = document.getElementById('top_bar_search_input').value;
    if (path != "" && searchValue != "") {
        window.location = path + "?search=" + searchValue;
    }
    else if (path != "") {
        window.location = path;
    }
}


function ValidateRegisterData() {
    var check = true;
    var placeHolder = "ctl00_ctl00_ctl00_ContentPlaceHolderDefault_L1_TipSLEditorUserControl_8_";
    var name = document.getElementById(placeHolder + "txtName").value;
    if (name == '' || name == undefined) {
        document.getElementById('divName').className = 'error';
        check = false;
    } else {
        document.getElementById('divName').className = "";
    }
    var phone = document.getElementById(placeHolder + 'txtPhone').value;
    if (phone == '' || phone == undefined || !validatePhoneNumber(phone)) {
        document.getElementById('divTelephone').className = 'error';
        check = false;
    } else {
        document.getElementById('divTelephone').className = '';
    }
    var email = document.getElementById(placeHolder + 'txtEmail').value;
    if (email == '' || email == undefined || !validateEmail(email)) {
        document.getElementById('divEmail').className = 'error';
        check = false;
    } else {
        document.getElementById('divEmail').className = 'rowEmail';
    }
    var address = document.getElementById(placeHolder + 'txtAdresse').value;
    if (address == '' || address == undefined) {
        document.getElementById('divAddress').className = 'error';
        check = false;
    } else {
        document.getElementById('divAddress').className = "";
    }
    var messageTitle = document.getElementById(placeHolder + 'txtMessageTitle').value;

    if (messageTitle == '' || messageTitle == undefined) {
        document.getElementById('divMessageTitle').className = 'error';
        check = false;
    } else {
        document.getElementById('divMessageTitle').className = "";
    }
    if (document.getElementById(placeHolder + 'txtContent').value == '') {
        document.getElementById('divContent').className = 'error';
        check = false;
    } else {
        document.getElementById('divContent').className = "";
    }
    return check;
}

function onGoogleSearchEnter(evt, path) {
    var keyCode = null;

    if (evt.which) {
        keyCode = evt.which;
    } else if (evt.keyCode) {
        keyCode = evt.keyCode;
    }
    if (13 == keyCode) {
        GoogleSearchPage(path);
        //frm.btnEnter.click();
        return false;
    }
    return true;
}

function ValidateForgotPasswordPage() {
    var placeHolder = "ctl00_ctl00_ctl00_ctl00_ContentPlaceHolderDefault_L1_L2_ForgotPassword_7_";

    document.getElementById(placeHolder + 'divError').innerHTML = "";
    document.getElementById(placeHolder + 'divSuccess').innerHTML = "";

    var email = document.getElementById(placeHolder + 'txtEmail').value;
    // var memberNo = document.getElementById(placeHolder + 'txtMemberNo').value;

    //    if (email == "" && memberNo == "") {
    //        document.getElementById(placeHolder + 'divError').innerHTML = document.getElementById("hdnFillFields").value;
    //        return false;
    //    }
    if (email == "") {
        document.getElementById(placeHolder + 'divError').innerHTML = document.getElementById("hdnFillFields").value;
        return false;
    }

    if (email != '' && !validateEmail(email)) {
        document.getElementById(placeHolder + 'divError').innerHTML = document.getElementById("hdnInvalidEmailAddress").value;
        return false;
    }
    return true;
}

function ReloadPage(url) {
    document.location.href = url;
}
