﻿//#################################################################################################
//#################################################################################################
//##                                                                                             ##
//##                                 LOAD AND INIT FUNCTIONS                                     ##
//##                                                                                             ##
//#################################################################################################
//#################################################################################################

var _lmkIsIE6 = (navigator.userAgent.indexOf("MSIE 6.") != -1);

var _lmkIsAllLmkJsLoaded = false;

function lmk_AllJsLoaded() {
    if (_lmkIsAllLmkJsLoaded) {
        lmk_PageInit();
    }
    else {
        if (window.addEventListener) {
            window.addEventListener('load', lmk_PageInit, false);
        }
        else if (window.attachEvent) {
            window.attachEvent('onload', lmk_PageInit);
        }
    }
    if (window.addEventListener) {
        window.addEventListener('load', lmk_PageLoad, false);
    }
    else if (window.attachEvent) {
        window.attachEvent('onload', lmk_PageLoad);
    }
}

function lmk_PageInit() {
    lmk_ShowHideDiv('LmkWaitLayerContainer', false);
    //if (lmk_IsDefined('_lmkDisplayBottomToolBar') && _lmkDisplayBottomToolBar) lmk_LoadBottomToolBar();
    if (lmk_IsDefined('_lmkDisplayToolbox') && _lmkDisplayToolbox) lmk_LoadToolbox();
    if (lmk_IsDefined('_lmkDisplayLmkArea') && _lmkDisplayLmkArea) lmk_LoadLmkArea();
}

function lmk_PageLoad() {
    if (typeof lmk_ProxyPageLoad == 'function') lmk_ProxyPageLoad();
}

//TODO: Do various crash test (back, refresh, etc...) on all kind of browsers
//TODO: Warn if the user does not support Flash or JS
//TODO: disable flash actions for the user (forward, rewind, stop, play)

//TODO: M - Antoine - Handle the cases "no DOCTYPE" and IE6
//TODO: M - Antoine - Test on Mac

var _lmkIsInternetExplorer = navigator.appName.indexOf("Microsoft") != -1;

var _lmkIsLmkAreaReady = false;
var _lmkToolboxCookieName = "LmkToolBox";
var _lmkToolBoxTop = 0;
var _lmkToolBoxLeft = 0;



//#################################################################################################
//#################################################################################################
//##                                                                                             ##
//##                                    GENERAL FUNCTIONS                                        ##
//##                                                                                             ##
//#################################################################################################
//#################################################################################################

function lmk_IsDefined(variable) {
    //return (typeof(window[variable]) != "undefined");
    return eval('(typeof(' + variable + ') != "undefined");');
}

function lmk_Wait(msecs) {
    var start = new Date().getTime();
    var cur = start
    while (cur - start < msecs) {
        cur = new Date().getTime();
    }
}

function lmk_GetFlashMovie(movieName) {
    var retValue = (_lmkIsInternetExplorer) ? window[movieName] : document[movieName];
    if (!retValue) retValue = (_lmkIsInternetExplorer) ? eval("document.all." + movieName) : eval("document." + movieName);
    return retValue;
}

//#################################################################################################
//#################################################################################################
//##                                                                                             ##
//##                                   FILL FORM FUNCTIONS                                       ##
//##                                                                                             ##
//#################################################################################################
//#################################################################################################

// Find a form by its name or index in all the page forms
function lmk_GetFormByNameOrIdOrIndex(name, id, index) {
    // Parsing all forms in the document to get the payment form
    var forms = document.forms;

    // Priority to index, because there might be several forms with the same name ! (cf camif)
    if (index > -1 && forms.length > index) return forms[index];

    for (var formIndex = 0; formIndex < forms.length; formIndex++) {
        var form = forms[formIndex];
        if ((name && form.name == name) || (id && form.id == id) || (index && formIndex == index)) {
            // Found
            return form;
        }
    }
    // If not found
    return null;
}


// Reset form
// In the future, it could set to "ResetValues" from XmlFormDescritpion
function lmk_ResetXmlForm(formJson) {
    var form = lmk_GetFormByNameOrIdOrIndex(formJson.ClientName, formJson.ClientId, formJson.ClientId);
    if (form && form != null) form.reset();
}

// TODO: Handle js exceptions
// Fills a form using formJson JSON object loaded from configuration
function lmk_FillXmlForm(formJson, autoPost) {

    // TODO: add Index in field class
    var form = lmk_GetFormByNameOrIdOrIndex(formJson.ClientName, formJson.ClientId, formJson.ClientIndex);

    if (form && form != null) {

        var formFields = form.elements;   //fields of the form in the document
        var jsonFields = formJson.Fields; //fields details retrieved from the server

        // In case form is reset, it will be filled again trough this function
        form.onreset = function() { lmk_FillXmlForm(formJson, autoPost); return false; };


        if (jsonFields) {
            // For each field detailed in formJson	
            for (var jsonFieldsIndex = 0; jsonFieldsIndex < jsonFields.length; jsonFieldsIndex++) {


                var found = 0; 	//reset the found var to false;
                var currentJsonField = jsonFields[jsonFieldsIndex];

                //if(jsonFields[jsonFieldsIndex].Value==null)	{errors.push('value not set for field '+jsonFields[jsonFieldsIndex].Name);}
                //if(jsonFields[jsonFieldsIndex].Type==null)	{errors.push('type not set for field ' +jsonFields[jsonFieldsIndex].Name);}

                //alert("looking for " + currentJsonField.Name);
                // Looking for the field in the document form
                for (var fieldIndex = 0; fieldIndex < formFields.length; fieldIndex++) {
                    var currentFormField = formFields[fieldIndex];

                    //alert(currentFormField.name);

                    // Check if current field name is indentical to JSON field name. The same test is done for Ids
                    if (currentJsonField.ClientValue && (currentJsonField.Name && currentFormField.name && (currentFormField.name.toLowerCase() == currentJsonField.Name.toLowerCase())) ||
                    (currentFormField.id && currentJsonField.Id && (currentFormField.id.toLowerCase() == currentJsonField.Id.toLowerCase()))) { 


                        // Simulate the user's focus (launches onFocus event)
                        // Temporary commented because IE raise an exception if object is not visible
                        //currentFormField.focus();

                        //------------------------------------ TEXT FIELD -----------------------------------//
                        // Just set the value
                        if (currentJsonField.Type == "text") {
                            currentFormField.value = currentJsonField.ClientValue;
                            //alert(currentJsonField.ClientValue);
                            //--------------------------------------- SELECT -------------------------------------//
                            // Set the value and update the onChange event to launch
                        }
                        else if (currentJsonField.Type == "select") {

                            // Browse options to select the right one
                            // if value attribute is missing, IE does not accept option.value 
                            // but option.text (for <option> 01 </option> rather than <option value="01"/>)
                            for (i = 0; i < currentFormField.length; i++) {
                                if (currentFormField.options[i].value == currentJsonField.ClientValue || currentFormField.options[i].text == currentJsonField.ClientValue) {
                                    currentFormField.selectedIndex = i;
                                }
                            }
                            // Usefull because change() cannot be fired
                            toEval = currentFormField.onchange; // Take the old event set to onChange
                            if (toEval) {
                            currentFormField.OldEventMethod = toEval; // Link the old event to the function name "OldEventMethod"
                                try{
                                currentFormField.OldEventMethod();     // Launch my new method
                                }catch(err){} // If the website JS crashes, the fillform has to continued
                            }

                            //--------------------------------------- RADIO -------------------------------------//
                        }
                        else if (currentJsonField.Type == "radio" && currentJsonField.ClientValue == currentFormField.value) {

                            currentFormField.checked = true;
                            if (currentFormField.onclick) {
                                try {
                                    currentFormField.onclick();     // Launch my new method
                                } catch (err) { } // If the website JS crashes, the fillform has to continued
                            }


                            //                            // Must parse the radio group to check the right value and uncheck others
                            //                            var controle;
                            //                            if (formJson.Index && formJson.Index > -1) {
                            //                                controle = eval("document.forms[" + formJson.Index + "]." + currentFormField.name); // Retrieve the control (the input)
                            //                            }
                            //                            else {
                            //                                controle = eval("document." + formJson.Name + "." + currentFormField.name); // Retrieve the control (the input)
                            //                            }
                            //                            var radioLength = controle.length; 													    // Get the number of radio options					
                            //                            for (var i = 0; i < radioLength; i++) {														    // Parse the radio options
                            //                                if (controle[i].value == currentJsonField.ClientValue) {					    // If it is my specified value
                            //                                    controle[i].checked = true;

                            //                                    //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Events must be triggered ====>>>>>>>>>>>>> TO BE TESTED
                            //                                    toEval = controle[i].onclick; 	// Take the old event set to onChange
                            //                                    if (!toEval) {
                            //                                    } else {
                            //                                        controle[i].OldEventMethod = toEval; // Link the old event to the function name "OldEventMethod"
                            //                                        controle[i].OldEventMethod();         // Launch my new method
                            //                                    }
                            //                                    //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

                            //                                } else {
                            //                                    controle[i].checked = false;
                            //                                }
                            //                            }

                            //--------------------------------------- CHECKBOX -------------------------------------//
                            // TODO: check if it is working
                        }
                        else if (currentJsonField.Type == "checkbox") {
                            if (currentJsonField.ClientValue == currentFormField.Value) {
                                currentFormField.checked = true;
                            }
                        }
                        else {
                            //-----------------------ERROR--------------------------- type not matched ------------------------//
                            //errors.push('type not matched for field '+currentFormField.name + '.Type specified is '+currentJsonField.Type);
                        }

                        currentFormField.autocomplete = "off";
                        //currentFormField.disabled = true;
                        currentFormField.style.backgroundColor = '#FFFFCC';
                        currentFormField.style.color = '#FF6633';
                        currentFormField.style.border = 'solid 1px #FF6633';
                        found = 1;
                    }
                }
                if (found == 0) {
                    if (currentJsonField.AddIfMissing && currentJsonField.ClientValue) {
                        lmk_AddHiddenField(form, currentJsonField.Name, currentJsonField.ClientValue);
                    }
                    //TODO: Antoine - M - Implement an exception handler (Ajax ?)
                    //else
                    //-----------------------WARNING--------------------------- no field found in the form for these details ------------------------//
                    //errors.push('Field not found '+currentJsonField.Name);
                }
            }
        }

        //if (autoPost) lmk_SubmitFormOnPageLoad(autoPostMethodPointer);
        if (autoPost) form.submit();
    }
}



function lmk_AddHiddenField(form, name, value) {
    if (form) {
        var hiddenField = document.createElement('input');
        hiddenField.setAttribute('type', 'hidden');
        hiddenField.setAttribute('name', name);
        hiddenField.setAttribute('value', value);
        form.appendChild(hiddenField);
    }
}



//#################################################################################################
//#################################################################################################
//##                                                                                             ##
//##                                  HIDE LAYERS FUNCTIONS                                      ##
//##                                                                                             ##
//#################################################################################################
//#################################################################################################



function lmk_ShowHideDiv(divId, display) {
    so = document.getElementById(divId);
    if (!so) return;
    if (display) {
        so.style.display = "inline";
    }
    else {
        //so.parentNode.removeChild(so);
        so.style.display = "none";
    }
    // Important to set focus to make sure that the browser redraws before executing more JS code.
    // SLE: cannot give the focus to an element that's not displayed --> js errors
    so.focus();
}

function lmk_DisplayHideLayer(display) {
    lmk_ShowHideDiv('LmkHideLayerContainer', display);
}










//#################################################################################################
//#################################################################################################
//##                                                                                             ##
//##                                        COOKIES FUNCTIONS                                    ##
//##                                                                                             ##
//#################################################################################################
//#################################################################################################

// OLD SET_COOKIE FUNTION
//function lmk_SetCookie(sName,sValue,sDays)
//{
//    var exdate=new Date();
//    exdate.setDate(exdate.getDate()+sDays);
//    document.cookie=sName+ "=" +escape(sValue)+ ((sDays==null) ? "" : ";expires="+exdate.toGMTString());
//}
//###################################################################
//    http://techpatterns.com/downloads/javascript_cookies.php
//###################################################################
function lmk_SetCookie(name, value, expires, path, domain, secure) {
    /*
    if the expires variable is set, make the correct 
    expires time, the current script below will set 
    it for x number of days, to make it for hours, 
    delete * 24, for minutes, delete * 60 * 24
    */
    var expires_date;
    if (expires) {
        // set time, it's in milliseconds
        var today = new Date();
        today.setTime(today.getTime());
        expires = expires * 1000 * 60 * 60 * 24;
        expires_date = new Date(today.getTime() + (expires));
    }

    document.cookie = name + "=" + escape(value) +
    ((expires) ? ";expires=" + expires_date.toGMTString() : "") +
    ((path) ? ";path=" + path : "") +
    ((domain) ? ";domain=" + domain : "") +
    ((secure) ? ";secure" : "");
}


// OLD SET_COOKIE FUNTION
//function lmk_GetCookie(sName)
//{
//    if (document.cookie.length>0)
//    {
//        var c_start = document.cookie.indexOf(sName + "=");
//        if (c_start!=-1)
//        { 
//            c_start=c_start + sName.length+1; 
//            c_end=document.cookie.indexOf(";",c_start);
//            if (c_end==-1) c_end=document.cookie.length;
//            return unescape(document.cookie.substring(c_start,c_end));
//        } 
//    }
//    return "";
//}
//###################################################################
//    http://techpatterns.com/downloads/javascript_cookies.php
//###################################################################
function lmk_GetCookie(check_name) {
    // first we'll split this cookie up into name/value pairs
    // note: document.cookie only returns name=value, not the other components
    var a_all_cookies = document.cookie.split(';');
    var a_temp_cookie = '';
    var cookie_name = '';
    var cookie_value = '';
    var b_cookie_found = false; // set boolean t/f default f

    for (i = 0; i < a_all_cookies.length; i++) {
        // now we'll split apart each name=value pair
        a_temp_cookie = a_all_cookies[i].split('=');


        // and trim left/right whitespace while we're at it
        cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

        // if the extracted name matches passed check_name
        if (cookie_name == check_name) {
            b_cookie_found = true;
            // we need to handle case where cookie has no value but exists (no = sign, that is):
            if (a_temp_cookie.length > 1) {
                cookie_value = unescape(a_temp_cookie[1].replace(/^\s+|\s+$/g, ''));
            }
            // note that in cases where cookie is initialized but no value, null is returned
            return cookie_value;
            break;
        }
        a_temp_cookie = null;
        cookie_name = '';
    }
    if (!b_cookie_found) {
        return null;
    }
}

// this deletes the cookie when called
function lmk_DeleteCookie(name, path, domain) {
    if (lmk_GetCookie(name)) document.cookie = name + "=" +
    ((path) ? ";path=" + path : "") +
    ((domain) ? ";domain=" + domain : "") + ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}







//#################################################################################################
//#################################################################################################
//##                                                                                             ##
//##                                       WINDOW SIZE FUNCTIONS                                 ##
//##                                                                                             ##
//#################################################################################################
//#################################################################################################


//#########################################################################################
/**************************************************
* Functions to retrieve the size of windows and divs
* Found at http://www.softcomplex.com/docs/get_window_size_and_scrollbar_position.html
**************************************************
* 
**************************************************/
//#########################################################################################

function lmk_ClientWidth() {

    //###########################
    //ADDED BY LIMONETIK
    //###########################
    //TODO: M - Antoine - Check compatibility IE, FX, Opera, Mac...
    return document.documentElement.clientWidth;

    //###########################
    //COMMENTED OUT BY LIMONETIK
    //###########################
    //	return lmk_FilterResults (
    //		window.innerWidth ? window.innerWidth : 0,
    //		document.documentElement ? document.documentElement.clientWidth : 0,
    //		document.body ? document.body.clientWidth : 0
    //	);
}
function lmk_ClientHeight() {

    //###########################
    //ADDED BY LIMONETIK
    //###########################
    //TODO: M - Antoine - Check compatibility IE, FX, Opera, Mac...
    return document.documentElement.clientHeight;

    //###########################
    //COMMENTED OUT BY LIMONETIK
    //###########################
    //	return lmk_FilterResults (
    //		window.innerHeight ? window.innerHeight : 0,
    //		document.documentElement ? document.documentElement.clientHeight : 0,
    //		document.body ? document.body.clientHeight : 0
    //	);
}
function lmk_ScrollLeft() {
    return lmk_FilterResults(
		window.pageXOffset ? window.pageXOffset : 0,
		document.documentElement ? document.documentElement.scrollLeft : 0,
		document.body ? document.body.scrollLeft : 0
	);
}
function lmk_ScrollTop() {
    return lmk_FilterResults(
		window.pageYOffset ? window.pageYOffset : 0,
		document.documentElement ? document.documentElement.scrollTop : 0,
		document.body ? document.body.scrollTop : 0
	);
}
function lmk_FilterResults(n_win, n_docel, n_body) {
    var n_result = n_win ? n_win : 0;
    if (n_docel && (!n_result || (n_result > n_docel)))
        n_result = n_docel;
    return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}





    
    


           


