/** [File : behaviour.js]
 *
 * Project:      Bluecycle
 * Version:      1.0
 * Created:      01/07/09
 * Last change:  01/07/09
 * Assigned to:  Diego Lago
 * Primary use:  Bluecyle website
 *
 */

/**
 * Suckerfish drop down menu
 * documented at http://htmldog.com/articles/suckerfish/dropdowns/
 */
sfHover = function() {
    var sfEls = document.getElementById('navigation').getElementsByTagName('LI');
    for (var i = 0; i < sfEls.length; i++) {
        sfEls[i].onmouseover = function() {
            this.className += ' sfhover';
        }
        sfEls[i].onmouseout = function() {
            this.className = this.className.replace(new RegExp(' sfhover\\b'), '');
        }
    }
}
if (window.attachEvent) window.attachEvent('onload', sfHover);

// dojo requires
//dojo.require('dojo.NodeList-fx');
//dojo.require("dijit.Dialog");
//dojo.require("dijit.form.TextBox");
//dojo.require("dijit.form.TimeTextBox");
//dojo.require("dijit.form.Button");
//dojo.require("dijit.form.DateTextBox");

// requires for tabs
//dojo.require("dojo.parser");
//dojo.require("dijit.layout.ContentPane");
//dojo.require("dijit.layout.TabContainer");
//dojo.require("dijit.form.Button");

dojo.addOnLoad(function() {
    // our dom is ready
    var isCometEnabled = true;
    if (dojo.byId("cometConfig")) {
        isCometEnabled = dojo.attr("cometConfig", "content") == "true";
    }
    console.info("isCometEnabled: " + isCometEnabled);

    /**
     * Refine search filters - No script
     * If JavaScript is enabled, a class is added to #outer-container,
     * the existance of this class will favour the display the checkbox-based filters.
     * If JavaScript is disabled, the default checkbox-based filters bar
     * won't show as their display is set to none in styles.css
     * Link-based navigations will show instead.
     */
    if (isCometEnabled) {
        dojo.query('#outer-container').addClass('js-enabled');
        dojo.query("div.turn-off").addClass('hide');
        
    }


    /*
     * If javascript is enabled make carousel panel visible
     */
    if (dojo.hasClass('outer-container', 'js-enabled')) {
    	 dojo.query("div[id^='carousel']").removeClass('hide');
    }
    
    if (dojo.hasClass('outer-container', 'js-enabled')) {
        dojo.query('#sub-navigation ul.script-on').removeClass('script-on');
    }

    if (isCometEnabled) {
        // show the set location link
        dojo.query(".hide-location-trigger").removeClass('hide-location-trigger');
        dojo.query("div[id^='location-trigger']").removeClass('hide');
        // hide sort button
        if (dojo.byId("sort_button"))
            dojo.style("sort_button", "display", "none");
        // after removing the sort button move the sort panel to left
        if (dojo.byId("sort-by"))
            dojo.style("sort-by", "left", "478px");
    }

    var moreImagesLink = dojo.byId("more_images");
    if (moreImagesLink) {
        dojo.style(moreImagesLink, "color", "#009DDC");
        dojo.connect(moreImagesLink, "onclick", function(e) {
            e.preventDefault();
            var mainImageLink = dojo.byId("main_image_link");
            hs.expand(mainImageLink);
        });
    }
    
    /**
     * Hide-Show extra refine options
     * When a "Show <span>more</span>" trigger link is clicked
     * we walk the DOM up to find the hidden list
     * containing the extra options and show them.
     */
    // without this check the code causes errors on SearchPage
    if (dojo.byId("category_selection") == null) {
        var more = dojo.query('a.more-options');
        more.connect('onclick', function(e) {
            // stop default behaviour on click
            e.preventDefault();

            // walk the dom to get ul with extra options
            var comAncestor = this.parentNode.parentNode.parentNode; // go to common ancestor
            var eleContainer = comAncestor.getElementsByTagName('div')[1];
            var extraOptions = eleContainer.getElementsByTagName('ul')[1];

            // get container for "more", "less"
            var filterState = this.getElementsByTagName('span')[0];

            // if there are extra options hidden toggle classes
            // to show extra options and update image arrow in trigger
            if (extraOptions) {
                dojo.toggleClass(extraOptions, 'hide');
                dojo.toggleClass(this, 'collapse');

                // update link text
                if (filterState.innerHTML === 'more') {
                    filterState.innerHTML = 'less';
                }
                else {
                    filterState.innerHTML = 'more';
                }
            }
        });
    }

    /**
     *if javascript is enabled
     * Hide-Show Home Page More News
     * When a "More details" link is clicked
     * we walk the DOM up to find the hidden content (body of the article) and display it.
     *
     * if javascript is disabled show the entire contents of the news panel and disable the link
     */

    dojo.query('#outer-container').addClass('js-enabled');

    var more = dojo.query('#news a.more-news');

    if (dojo.hasClass('outer-container', 'js-enabled')) {

        dojo.query("#news a.more-news").toggleClass('collapse');
        dojo.query("#news a.more-news").toggleClass('hide');
        dojo.query("#news .mod-main").toggleClass('hide');

        more.connect('onclick', function(e) {
            // stop default behaviour on click
            e.preventDefault();

            dojo.query("#news .mod-main").toggleClass('hide');
            dojo.toggleClass(this, 'collapse');

            // update link text
            if (this.innerHTML === 'More details') {
                this.innerHTML = 'Close';
            }
            else {
                this.innerHTML = 'More details';
            }
        });
    }

    /**
     * Timers
     * The timers are flash movies embedded with swf object
     * http://code.google.com/p/swfobject/wiki/documentation
     * SWFObject is a small Javascript file used for embedding Adobe Flash content.
     * The script can detect the Flash plug-in in all major web browsers (on Mac and PC)
     * and is designed to make embedding Flash movies as easy as possible.
     * It is also very search engine friendly, degrades gracefully, can be used in
     * valid HTML and XHTML 1.0 documents*, and is forward compatible, so it should work for years to come.
     */
    // each row of results (class "result") gets a timer flash movie with the right id
    // movies are hidden until they are played
    dojo.query('.result').forEach(function(node, index, arr) {
        var flashvars = {};
        var params = {
            play: 'false',
            loop: 'false',
            quality: 'high',
            wmode: 'transparent'
        };
        var attributes = {
            id: 'result' + (index + 1) + 'Movie',
            name: 'result' + (index + 1) + 'Movie',
            style: 'visibility: hidden; height: 0'
        };
        // without this check the code causes errors on SearchPage
        if (typeof swfobject !== "undefined") {
            swfobject.embedSWF("swf/timer.swf", 'result-' + (index + 1) + '-timer', "170", "30", "9.0.0", "swf/expressInstall.swf", flashvars, params, attributes);
        }
    });

    /**
     * Tabs
     * To assign a Dojo object to a div tag, first we call the widgets constructor and assign the result to a handle. We create a TabContainer object and a ContentPane object.
     * Notice the constructor takes 2 parameters. A list of widget attributes, and the id of the HTML element we want to apply the control to.
     * The attribute list would appear as HTML attributes if we were defining everything in markup.
     * Next, we associate the tabs with the tab container, add them as children to it. However, nothing is displayed yet.
     * To display the control in the page, we call the startup method for the control. That does the trick everything gets built and the tab is displayed
     * dojo.style(dojo.byId("tab2"),"visibility","hidden");  dojo.style(dojo.byId("tab2"), "display", "none");
     *
     * default settings are applied in the html files to support browsers which have javascript disabled. Below checks for this
     * and if javascript is enabled all the attributes set in the html files, which are applicable in case of
     * disabled javascript only, are removed.
     */

    dojo.query('#outer-container').addClass('js-enabled');

    if (dojo.hasClass('outer-container', 'js-enabled')) {

        dojo.query("#tab2 h3.no-javascript").toggleClass('hide');
        dojo.query("#tab2 hr.divider").toggleClass('hide');
        dojo.query("#tab1 h3.no-javascript").toggleClass('hide');
        if (dojo.byId('seller-form')) {
            dojo.removeAttr('seller-form', "action");
        }

        var tc = new dijit.layout.TabContainer(
        {
            style:"width:100%;height:160px;",
            selected:true
        },
                "mainTabContainer"
                );

        var tab1 = new dijit.layout.ContentPane(
        {
            title:"I'm a buyer"
        },
                "tab1"
                );

        var tab2 = new dijit.layout.ContentPane(
        {
            title:"I'm a seller"
        },
                "tab2"
                );

        var tc = dijit.byId("mainTabContainer");
        var domNode = dojo.byId("registration");

        // without this check the code causes errors on SearchPage
        if (tc != null && domNode != null) {
            if (dojo.hasClass(domNode, 'buyer-only')) {
                tc.addChild(tab1);
            } else {
                tc.addChild(tab1);
                tc.addChild(tab2);
            }
            tc.startup();
        }

        // without this check the code causes errors on SearchPage
        if (dojo.byId('seller-form')) {
            dojo.attr('seller-form', "action", "https://" + window.location.host + "/autosalvage/login.do");
        }
    }
    // without this check the code causes errors on SearchPage
    if (dojo.byId('buyer-form')) {
        qS = dojo.attr('buyer-form', "action");
        qS = qS.substring(qS.indexOf('?'));
        dojo.attr('buyer-form', "action", "https://" + window.location.host + "/car-salvage-auctions/login" + qS);
    }
});

function previewImage(img) {
    var src = dojo.attr(img.parentNode, "href");
    //console.log(src);
    dojo.fadeOut({
        node : 'main_image',
        delay: 50,
        onEnd: function() {
            dojo.attr('main_image', "src", src);
            dojo.fadeIn({node:"main_image", delay: 10}).play();
        }
    }).play();
}

function expandGallery(link) {
    return hs.expand(link);
}

String.prototype.endsWith = function(str) {
    return (this.match(str + "$") == str);
};

