/*
utilities.js Common functionnality for soscuisine.com
Dependencies : Prototype JavaScript framework 1.6
               Macromedia Flash Player Version Detection (1.6) (for flash functions only)
*/
if (typeof Prototype == 'undefined')
    throw ("SOSCuisine Application requires the Prototype JavaScript framework");

var SOSCuisine =
{
    version: '0.1',
    prototypeVersion: parseFloat(Prototype.Version.split(".")[0] + "." + Prototype.Version.split(".")[1]),

    config: {
        urlRoot: "",
        showUserSettingsOnLoad: false,
        isPrintVersion: false,
        cookieEnabled: (document.cookie.indexOf("language") != -1) ? true : false,
        languagesUrl: {}
    },

    printPreview: function printPreview(withOption)
    {
        if (withOption == true)
        {
            SOSCuisine.personalizedPrintPreferences.show();
        }
        else
        {
            window.open(document.URL + "&print_preview=1");
        }
    },

    /* Search box */
    searchBox:
    {
        search: function()
        {
            if (document.getElementById("search_site").checked == true)
            {
                this.googleSearch();
            }
            else
            {
                this.recipeSearch();
            }
            return true;
        },

        googleSearch: function()
        {
            var searchForm = document.getElementById('searchForm');
            searchForm.action = "http://www.google.com/custom";
            searchForm.target = 'google_window';
            document.getElementById('searchForm').method = "get";
            document.getElementById('searchInput').name = "q";
        },

        recipeSearch: function()
        {
            var searchForm = document.getElementById('searchForm');
            searchForm.action = document.getElementById('url_root').value + "recipe_browse_search.php";
            searchForm.target = '';
            document.getElementById('searchForm').method = "post";
            document.getElementById('searchInput').name = "keyword_search_string";
        }
    },

    /* Ingredient Search*/
    ingredientSearch:
    {
        validate: function(id)
        {
            this.cleanInput(document.getElementById("keyword_search_string_ingredient_1"), document.getElementById("default_keyword_search_string_ingredient_1"));
            this.cleanInput(document.getElementById("keyword_search_string_ingredient_2"), document.getElementById("default_keyword_search_string_ingredient_2"));
            this.cleanInput(document.getElementById("keyword_search_string_ingredient_3"), document.getElementById("default_keyword_search_string_ingredient_3"));
        },

        cleanInput: function(obj, defaultInput)
        {
            if (obj.value == defaultInput.value)
            {
                obj.value = "";
                return true
            }
            return false;
        }
    },

    /* TAb control for recipe page */
    tabControl:
    {
        tabs: ["RecipeContent", "NutritionInfoContent", "MyRating", "MyNotes", "Comments"],

        show: function(id)
        {
            this.switchStyle(id, "block", "selected");
        },

        hide: function(id)
        {
            this.switchStyle(id, "none", "");
        },

        switchStyle: function(_id, _display, _className)
        {
            var content = document.getElementById(_id);
            if (content != null)
            {
                var tab = document.getElementById("tab" + _id);
                if (tab != null)
                {
                    content.style.display = _display;
                    tab.className = _className;
                }
            }
        },

        changeTab: function(tab, id)
        {
            for (i = 0; i < this.tabs.length; i++)
            {
                if (this.tabs[i] == tab)
                {
                    this.show(this.tabs[i] + "_" + id);
                }
                else
                {
                    this.hide(this.tabs[i] + "_" + id);
                }
            }
        }
    },

    /*
    (April 11 2006) Microsoft 
    To create Web pages that load interactive controls that respond
    immediately to user input, use Microsoft JScript to load controls from
    external script files. You cannot write script elements inline with the
    main HTML page to load your control externally. If the script is
    written inline programmatically, for example with the writeln function,
    the loaded control will behave as if it was loaded by the HTML document
    itself and will require activation. To ensure a control is interactive
    when it is loaded, use one of the following techniques to load your
    control from an external file.    
    */

    flash:
    {
        majorVersion: 9,
        minorVersion: 0,
        requiredRevision: 0,

        write: function(url, width, height)
        {
            if (DetectFlashVer(this.majorVersion, this.minorVersion, this.requiredRevision))
            {
                document.write('<object type="application/x-shockwave-flash" data="' + SOSCuisine.common.escapeHtml(url) + '" height="' + SOSCuisine.common.escapeHtml(height) + '" width="' + SOSCuisine.common.escapeHtml(width) + '"">');
                document.write('<param name="movie" value="' + SOSCuisine.common.escapeHtml(url) + '" />');
                document.write('<param value="opaque" name="wmode"/>');
                document.write('<embed wmode="opaque" pluginspage="http://www.macromedia.com/go/getflashplayer" quality="high" src="' + SOSCuisine.common.escapeHtml(url) + '" type="application/x-shockwave-flash" width="' + SOSCuisine.common.escapeHtml(width) + '" height="' + SOSCuisine.common.escapeHtml(height) + '"></embed>;');
                document.write('</object>');
            }
            else
            {
                document.write('<div class="flash_warning_container"><div class="flash_warning not_printable" style="width:' + (width - 16) + 'px; height:' + (height - 28) + 'px;">');
                document.write(SOSCuisine.config.flashWarningText);
                document.write('<p><a href="http://www.adobe.com/go/getflash/">' + SOSCuisine.config.flashDownloadText + '</a></p>');
                document.write('</div></div>');
            }
        }
    },

    loginBox:
    {
        clear: function(obj)
        {
            obj.value = "";
        },

        show: function(obj)
        {
            obj.style.display = "inline";
            obj.focus();
        },

        hide: function(obj)
        {
            obj.style.display = "none";
        }
    },

    ads:
    {
        hide: function()
        {
            var ads = SOSCuisine.common.getElementsByClassName("ads", "div");
            for (var i = 0; i < ads.length; i++)
            {
                var hideAds = false;
                var item = ads[i];
                var adsContainer = document.getElementById(item.id + '_ads');
                var img = adsContainer.getElementsByTagName("img")[0];

                if (adsContainer.offsetHeight < 14)
                {
                    hideAds = true;
                }

                if (img && img.src == 'http://m1.2mdn.net/viewad/817-grey.gif')
                {
                    hideAds = true;
                }

                if (hideAds == true)
                {
                    // Some browsers won't load images when his (or his container's)
                    // style attribute "display" equal "none" and we want the 
                    // images to load (at least for statistics).
                    // To achieve the same result visually while allowing
                    // the images to load, we position the images off-screen.
                    item.style.position = 'absolute';
                    item.style.left = '-9999px';
                }
            }
        }
    },

    common:
    {
        globalOnLoad: function()
        {
            SOSCuisine.ads.hide();
            SOSCuisine.customElement.initialize();
            SOSCuisine.userSetting.initialize();
        },

        preloadedImages: [],
        preloadImage: function(imageUrl)
        {
            var img = new Image();
            img.src = imageUrl;
            this.preloadedImages.push(img);
        },

        imageTooltips: {
            img: null,
            container: null,
            recipeId: null,
            recipeInformationContainer: null,
            tooltipTimeout: null,
            event: null,
            cache: []
        },

        showTooltips: function(obj, contentId, contentWidth)
        {
            window.tipobj.style.backgroundImage = "";
            window.tipobj.style.height = "auto";

            document.getElementById('dhtmlpointer').src = SOSCuisine.config.urlRoot + 'scripts/ddtooltip2/arrow2.gif';
            toolTipsContent = document.getElementById(contentId).innerHTML;
            ddrivetip(toolTipsContent, contentWidth);
            SOSCuisine.common.addListener(obj, "mouseout", hideddrivetip, true);
        },

        showRecipeInformationTooltip: function(event, obj, imgPath, recipeId)
        {
            this.imageTooltips.recipeId = recipeId;

            var pointer = document.getElementById('dhtmlpointer');
            document.getElementById('dhtmlpointer').style.display = "none"
            document.getElementById('dhtmlpointer').src = "";

            if (this.imageTooltips.container == null)
            {
                this.imageTooltips.container = new Element("div");
                this.imageTooltips.img = new Element("img");
                this.imageTooltips.recipeInformationContainer = new Element("div");

                this.imageTooltips.recipeInformationContainer.addClassName("recipeInformationTooltip");
                this.imageTooltips.recipeInformationContainer.hide();

                this.imageTooltips.container.insert(this.imageTooltips.img);
                this.imageTooltips.container.insert(this.imageTooltips.recipeInformationContainer);
                document.body.appendChild(this.imageTooltips.container);

                this.imageTooltips.container.hide();
            }

            this.imageTooltips.img.src = imgPath;

            window.tipobj.style.height = "200px";

            this.setSelectVisibility("hidden");
            ddrivetip(this.imageTooltips.container.innerHTML, 600);

            window.tipobj.oldBorderWidth = window.tipobj.style.borderWidth;
            window.tipobj.oldBackgroundColor = window.tipobj.style.backgroundColor;
            window.tipobj.style.borderWidth = "0px";
            window.tipobj.style.backgroundColor = "transparent";

            this.cleanRecipeInformationTooltip();
            
            
            if (this.imageTooltips.cache[recipeId])
            {
                window.setTimeout(function()
                {
                    if (this.imageTooltips.recipeId == recipeId)
                    {
                        this.updateRecipeInformationTooltip(this.imageTooltips.cache[recipeId]);
                    }
                } .bind(this), 200)

            }
            else
            {
                // Load recipe information
                new Ajax.Request(SOSCuisine.config.urlRoot + "recipe_information_tooltip.php", {
                    method: "get",
                    encoding: 'iso-8859-1',
                    parameters: { mode: "ajax", recipe_id: recipeId },
                    onSuccess: function(transport)
                    {
                        if (this.imageTooltips.recipeId == recipeId)
                        {
                            var response = transport.responseText || "";
                            this.updateRecipeInformationTooltip(response);
                        }
                        this.imageTooltips.cache[recipeId] = response;                        
                    } .bind(this)
                });
            }
			
            Element.observe(obj, "mouseout", function()
            {
                window.tipobj.style.borderWidth = window.tipobj.oldBorderWidth;
                window.tipobj.style.backgroundColor = window.tipobj.oldBackgroundColor;
                this.setSelectVisibility("visible");
                hideddrivetip();
                Event.stopObserving(obj, "mouseout");
            } .bind(this));
        },

        updateRecipeInformationTooltip: function(content)
        {
            var recipeInformationContainers = $$('#dhtmltooltip .recipeInformationTooltip')[0];
            var recipeImg = $$('#dhtmltooltip img')[0];

            var pointer = document.getElementById('dhtmlpointer');

            document.getElementById('dhtmlpointer').style.display = ""
            document.getElementById('dhtmlpointer').src = SOSCuisine.config.urlRoot + 'scripts/ddtooltip2/arrow2.gif';

            window.tipobj.style.width = (recipeImg.offsetWidth + 340) + "px";
            window.tipobj.style.height = "auto";

            window.tipobj.style.borderWidth = window.tipobj.oldBorderWidth;
            window.tipobj.style.backgroundColor = window.tipobj.oldBackgroundColor;

            recipeInformationContainers.style.backgroundImage = "";
            recipeInformationContainers.style.height = "auto";
            recipeInformationContainers.innerHTML = content;
            recipeInformationContainers.show();
        },

        cleanRecipeInformationTooltip: function()
        {
            var recipeInformationContainers = $$('#dhtmltooltip .recipeInformationTooltip');
            if (recipeInformationContainers.length > 0)
            {
                recipeInformationContainers[0].innerHTML = "";
            }

        },

        setSelectVisibility: function(visible)
        {
            nodes = document.getElementsByTagName('select');
            for (var i = 0; i < nodes.length; i++)
            {
                nodes[i].style.visibility = visible;
            }
        },

        addListener: function(element, type, expression, bubbling)
        {
            bubbling = bubbling || false;
            if (window.addEventListener)  // standard way
            {
                element.addEventListener(type, expression, bubbling);
                return true;
            }
            else if (window.attachEvent) // IE way
            {
                element.attachEvent('on' + type, expression);
                return true;
            }
            else  // should never happen
            {
                return false;
            }
        },

        addLoadEvent: function(func)
        {
            var oldonload = window.onload;
            if (typeof window.onload != 'function')
            {
                window.onload = func;
            }
            else
            {
                window.onload = function()
                {
                    if (oldonload)
                    {
                        oldonload();
                    }
                    func();
                }
            }
        },

        /**
        * Converts HTML special characters to their entity equivalents.
        *
        * Warning: do not use prototype's escapeHTML as it is broken and doesn't escape quote (")
        *          unless they eventually fix it, then we will switch over.
        *
        *@param string s String to be escaped for HTML
        *@return string
        */
        escapeHtml: function(s)
        {
            return s.toString().replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&#34;').replace(/'/g, '&#39;');
        },

        getElementsByClassName: function(clsName, tag)
        {
            var retVal = new Array();

            if (tag == null)
            {
                tag = "*";
            }

            var elements = document.getElementsByTagName(tag);

            for (var i = 0; i < elements.length; i++)
            {
                var classes = elements[i].className.split(" ");
                for (var j = 0; j < classes.length; j++)
                {
                    if (classes[j] == clsName)
                    {
                        retVal.push(elements[i]);
                    }
                }
            }
            return retVal;
        }
    },

    customElement:
    {
        supportedCssClass: [
                                ["blink", "a", function(elm) { this.doBlink(elm) } ],
                                ["pulse", "a", function(elm) { this.doPulse(elm) } ]
                           ],

        initialize: function()
        {
            for (var i = 0; i < this.supportedCssClass.length; i++)
            {
                nodes = SOSCuisine.common.getElementsByClassName(this.supportedCssClass[i][0], this.supportedCssClass[i][1]);
                for (var j = 0; j < nodes.length; j++)
                {
                    this.supportedCssClass[i][2].call(this, nodes[j]);
                }
            }
        },

        doBlink: function(elm)
        {
            elm.originalColor = elm.style.color;
            var count = 0;
            var intervalId = window.setInterval(function()
            {
                if (elm.originalColor == elm.style.color)
                {
                    elm.style.color = '#666';
                }
                else
                {
                    elm.style.color = elm.originalColor;
                }
                if (count++ == 20)
                {
                    window.clearInterval(intervalId);
                    elm.style.color = elm.originalColor;
                }
            }, 300)
        },

        doPulse: function(elm)
        {
            new Effect.Pulsate(elm, { pulses: 3, duration: 1 });
        }
    },

    overlay: {
        showOverlay: function()
        {
            document.getElementById("overlay").style.visibility = "visible";
            document.getElementsByTagName("body")[0].style.overflow = "hidden";
        },

        hideOverlay: function()
        {
            document.getElementById("overlay").style.visibility = "hidden";
            document.getElementsByTagName("body")[0].style.overflow = "";
        }
    },

    personalizedPrintPreferences:
    {

        initialized: false,

        show: function()
        {
            this.setSelectVisibility('hidden');
            if (window.scrollTo)
            {
                window.scrollTo(0, 0);
            }
            SOSCuisine.overlay.showOverlay();
            document.getElementById("modal_dialog_ppp").style.visibility = "visible";
            var sidebarAds = document.getElementById("sidebar_ads");
            if (sidebarAds !== null)
            {
                sidebarAds.style.display = "none";
            }
            if (!this.initialized)
            {
                this.initCustomBehavior();
            }

        },

        hide: function()
        {
            document.getElementById("modal_dialog_ppp").style.visibility = "hidden";
            this.setSelectVisibility('visible');
            SOSCuisine.overlay.hideOverlay();
            var sidebarAds = document.getElementById("sidebar_ads");
            if (sidebarAds !== null)
            {
                sidebarAds.style.display = "block";
            }
        },

        setSelectVisibility: function(visible)
        {
            nodes = document.getElementsByTagName('select');
            for (var i = 0; i < nodes.length; i++)
            {
                nodes[i].style.visibility = visible;
            }
        },

        validateChild: function(obj)
        {
            var childContainer = document.getElementById(obj.id + "_child");
            var childValue = (obj.checked == true) ? "" : "disabled";
            if (childContainer != null)
            {
                childInputs = childContainer.getElementsByTagName("input");
                for (var i = 0; i < childInputs.length; i++)
                {
                    childInputs[i].disabled = childValue;
                }
            }
            this.updateSubmit();
        },

        updateSubmit: function()
        {
            var container = document.getElementById('modal_dialog_content_inner_ppp');
            var inputs = container.getElementsByTagName("input");
            var count = 0;
            var MandatoryCount = 0;
            for (var i = 0; i < inputs.length; i++)
            {
                if (inputs[i].type == "checkbox" && inputs[i].checked == true && inputs[i].className == "mandatory")
                {
                    count++;
                }
                if (inputs[i].className == "mandatory")
                {
                    MandatoryCount++;
                }
            }

            if (count || MandatoryCount == 0)
            {
                document.getElementById('modal_submit').disabled = "";
            }
            else
            {
                document.getElementById('modal_submit').disabled = true;
            }
        },

        post: function(printForm, url)
        {
            if (url == '')
            {
                printForm.action = document.URL + "&print_preview=1"; ;
            }
            else
            {
                if (url.indexOf('?') == -1)
                {
                    printForm.action = url + "?print_preview=1"; ;
                }
                else
                {
                    printForm.action = url + "&print_preview=1"; ;
                }
            }
            this.hide();
            printForm.submit();
        },

        initCustomBehavior: function()
        {
            for (var i in this.custom)
            {
                if (this.custom[i].initialize)
                {
                    this.custom[i].initialize();
                }
            }
        },

        custom:
       {
           recipe:
           {
               initialize: function()
               {
                   var selectedRecipes = document.getElementById('selected_recipes');
                   if (selectedRecipes)
                   {
                       var container = document.getElementById('modal_dialog_content_ppp');
                       var containerRecipe = document.getElementById('container_recipe');
                       if (!containerRecipe && selectedRecipes)
                       {
                           containerRecipe = document.createElement("div");
                           containerRecipe.id = "container_recipe";
                           container.appendChild(containerRecipe);
                           containerRecipe.innerHTML = selectedRecipes.innerHTML;
                           selectedRecipes.innerHTML = "";
                       }
                       containerRecipe.style.display = "none";
                   }
               },

               showSelectedRecipe: function()
               {
                   var containerInner = document.getElementById('modal_dialog_content_inner_ppp');
                   var containerRecipe = document.getElementById('container_recipe');
                   containerInner.style.display = "none";
                   containerRecipe.style.display = "block";
                   var selectedRecipeInput = document.getElementById('selected_recipes_menu');
                   if (selectedRecipeInput.checked == false)
                   {
                       selectedRecipeInput.click();
                   }
               },

               back: function()
               {
                   var containerRecipe = document.getElementById('container_recipe');
                   var containerInner = document.getElementById('modal_dialog_content_inner_ppp');
                   containerRecipe.style.display = "none";
                   containerInner.style.display = "block";
               },

               addRemove: function(obj, recipeId, recipeGrpId)
               {
                   recipeInput = document.getElementById("post_" + recipeId);
                   recipeGroupInput = document.getElementById("post_" + recipeGrpId);
                   if (obj.checked == true)
                   {
                       recipeInput.name = recipeInput.oldName;
                       recipeGroupInput.name = recipeGroupInput.oldName;
                   }
                   else
                   {
                       recipeInput.oldName = recipeInput.name;
                       recipeGroupInput.oldName = recipeGroupInput.name;
                       recipeInput.name = "";
                       recipeGroupInput.name = "";
                   }
               },

               toggleRecipe: function(value)
               {
                   var containerRecipe = document.getElementById('container_recipe');
                   nodes = containerRecipe.getElementsByTagName('input');
                   for (var i = 0; i < nodes.length; i++)
                   {
                       if (nodes[i].type == "checkbox")
                       {
                           if (nodes[i].checked != value)
                           {
                               nodes[i].checked = !value;
                               nodes[i].click();
                           }
                       }
                   }
               }
           }
       }
    },

    warning: {

        addWarning: function(errorMsg)
        {
            if (!SOSCuisine.config.isPrintVersion)
            {
                var warningContainer = $('warning_container');
                warningContainer.innerHTML += errorMsg + "<br />";
                warningContainer.style.display = "block";
            }
        },

        clearAllWarning: function()
        {
            var warningContainer = $('warning_container');
            warningContainer.innerHTML = "";
            warningContainer.style.display = "none";
        }
    },

    userSetting: {

        container: null,

        initialize: function()
        {
            if (SOSCuisine.config.showUserSettingsOnLoad)
            {
                if (SOSCuisine.config.cookieEnabled)
                {
                    this.container = document.getElementById("modal_dialog_content_user_settings");
                    this.setSelectVisibility("hidden");
                    this.show();
                    this.loadContent();
                }
                else
                {
                    SOSCuisine.warning.addWarning($('warning_no_cookie').innerHTML);
                }
            }
        },

        loadContent: function()
        {
            this.container.style.backgroundImage = "url(" + SOSCuisine.config.urlRoot + "media/images/ajax-loader.gif)";
            this.container.style.height = "200px";
            new Ajax.Request(SOSCuisine.config.urlRoot + "user_settings.php", {
                method: "get",
                encoding: 'iso-8859-1',
                parameters: { mode: "ajax" },
                onSuccess: function(transport)
                {
                    this.container.style.height = "auto";
                    this.container.style.backgroundImage = "";
                    var response = transport.responseText || "";
                    this.container.innerHTML = response;
                } .bind(this)
            });
        },

        setSelectVisibility: function(visible)
        {
            nodes = document.getElementsByTagName('select');
            for (var i = 0; i < nodes.length; i++)
            {
                nodes[i].style.visibility = visible;
            }
        },

        show: function()
        {
            if (window.scrollTo)
            {
                window.scrollTo(0, 0);
            }
            SOSCuisine.overlay.showOverlay();
            document.getElementById("modal_dialog_user_settings").style.visibility = "visible";
            var sidebarAds = document.getElementById("sidebar_ads");
            if (sidebarAds !== null)
            {
                sidebarAds.style.display = "none";
            }
        },

        hide: function()
        {
            document.getElementById("modal_dialog_user_settings").style.visibility = "hidden";
            var sidebarAds = document.getElementById("sidebar_ads");
            if (sidebarAds !== null)
            {
                sidebarAds.style.display = "block";
            }
            SOSCuisine.overlay.hideOverlay();
        },

        switchLanguage: function()
        {
            var containerFrench = $('container_region_french');
            var containerEnglish = $('container_region_english');
            if (containerFrench.style.display == "none")
            {
                containerEnglish.style.display = "none";
                containerFrench.style.display = "block";
            }
            else
            {
                containerEnglish.style.display = "block";
                containerFrench.style.display = "none";
            }
        },

        switchRegion: function(region)
        {
            var formUserSettings = $("formUserSettings");
            var url = location.href;
            var lang = $('language').value;
            if (typeof SOSCuisine.config.languagesUrl[lang] != "undefined")
            {
                url = SOSCuisine.config.languagesUrl[lang];
            }
            formUserSettings.action = url;
            $("region").value = region;

            formUserSettings.submit();
        }
    },

    advanceSearchForm:
    {
        inputOnBlur: function(obj)
        {
            if (obj.value == "")
            {
                Element.removeClassName(obj, "selected");
            }
            else
            {
                Element.addClassName(obj, "selected");
            }
        },

        checkboxOnClick: function(obj)
        {
            var elem = Element.next(obj);
            if (obj.checked == true)
            {
                Element.addClassName(elem, "selected");
            }
            else
            {
                Element.removeClassName(elem, "selected");
            }
        },

        selectOnClick: function(obj)
        {
            if (obj.selectedIndex == 0)
            {
                Element.removeClassName(obj, "selected");
            }
            else
            {
                Element.addClassName(obj, "selected");
            }
        }
    }
};

SOSCuisine.common.addLoadEvent(SOSCuisine.common.globalOnLoad);
