// Overwrite dojos dojo._loadUri method since it seems to be broken in FF3.5
//dojo.require("doox.tools.TekUser");
dojo.require("doox.widgets.Konami");
//dojo.require("doox.tools.Overlay");

function appendAd(id) { 
    var pos = document.getElementById("ad" + id); 
    var ad = document.getElementById("tmpad" + id);
    if (pos && ad) { 
        pos.style.height = "auto"; 
        var script = ad.getElementsByTagName("script"); 
        if (script != null) { 
            for (var i = 0; i < script.length; i++) { 
                var s = script[i]; 
                s.src.replace = "http://static.gfx.no/common/js/empty.js"; 
            }
        }
        var body = ad.parentNode; 
        body.removeChild(ad); 
        pos.innerHTML = ""; 
        pos.appendChild(ad); 
    } 
}

/**
 * Callback-function for the hideTextOnSelect-function. Should not be used
 * directly.
 */
function hideTextOnSelectCb(evt) {
    var elem = evt.target;
    var type = evt.type;

    if (type == 'blur') {
        if (elem.value == '') {
            elem.value = elem.initialValue;
        }
    }

    if (type == 'focus') {
        if (elem.value == elem.initialValue) {
            elem.value = '';
        }
    }
}

/**
 * Function to hide initial text in a input text-field.
 * Hooks up the needed callbacks and handles everything for you just
 * set the initial text in the 'value'-attribute of the input-field 
 * and add the handler to your elements with this function.
 */
function hideTextOnSelect(elem) {
    elem.initialValue = elem.value;
    dojo.connect(elem, "onfocus", hideTextOnSelectCb);
    dojo.connect(elem, "onblur", hideTextOnSelectCb);
}

/**
 * Go directly to product function
 *
 */

function gotoProduct(evt) {
    var elem = dojo.byId("chooseMobile");
    if (elem) {
        var value = evt.target.value;
        var url = elem.action;
        
        document.location.href=url+'?productId='+value;
    }
}

function addGoto() {
    var elem = dojo.byId("selectChooseMobile");
    dojo.connect(elem, "onchange", gotoProduct);

}

function tekUser() {
//    var user = new doox.tools.TekUser();
    user.call('register');
}

function addOnEvents() {
    //tekUser();
    // Add hide-text-on-select handler to the product search input field
    var elem = dojo.byId("productSearchInput");
    if (elem)
        hideTextOnSelect(elem);
    // Main search
    var elem = dojo.byId("searchUbiquitousField");
    if (elem)
        hideTextOnSelect(elem);
    // Filter searching
    var elem = dojo.byId("filter");
    if (elem)
        hideTextOnSelect(elem);
    // If frontpage
    var elem = dojo.byId("frontPage");
    if (elem)
        addClicksUrl();
}

function addClicksUrl() {
    dojo.query(".preamble").forEach(function(p, pos) {
        if (!dojo.hasClass(p, 'notice')) {
            dojo.query("a", p).forEach(function(link) {
                link.posId = pos;
                dojo.connect(link, 'onmousedown', addClicksUrlCb);
            });
        }
    });

}

function addClicksUrlCb(evt) {
    var elem = evt.target;
    while (elem && elem.tagName != 'A') {
        elem = elem.parentNode;
    }

    var position = elem.posId;
    if (elem.href && elem.href.indexOf('http://go.tek.no/') == -1) {
        elem.href = 'http://go.tek.no/?url=' + encodeURIComponent(elem.href) + '&pid=' + position;
    }
}



/**
 * Function for show or hide spoiler text in article forum replies
 *
 */

function openClose(id) {
    var elem = dojo.byId(id);
    if (elem.style.display == "none" || elem.style.display == "")
        elem.style.display = "block";
    else
        elem.style.display = "none";
}

function addSelectedMenuItem() {
    var elemsInFocus = dojo.query("ul.inFocus li");
    for (var i = 0; i < elemsInFocus.length; i++)
        dojo.connect(elemsInFocus[i], "onclick", changeSelected);
}

/* dojo.addOnLoad(addHoverSectionMenu); */



/**
 * Adds product finder mouse events.
 *
 */
function addPopupSearch(query) {
    dojo.query(query).forEach(function(elem) {
        dojo.connect(elem, "onclick", productFinder);
    });
    var urlHash = window.location.hash;
    if (urlHash.indexOf('finn') == 1) {
        productFinder();
    }
}

/**
 * Call url where a spesific product finder is located
 *
 */
function productFinder(evt) {
    if (evt)
        evt.preventDefault();
    
    // Add loading so the user doesn't think that nothing is loading
    var loading = document.createElement("img");
    dojo.addClass(loading, "loading");
    loading.src = "http://static.new.gfx.no/images/main/spinner.gif";
    dojo.style(loading, {
        "position": "absolute",
        "top": "152px",
        "left": "50%",
        "width": "32px",
        "margin-left": "-16px",
        "background": "#fff"
    });
    document.body.appendChild(loading);
    document.body.scrollIntoView();

    // Load the required dojo modules
    dojo.require("doox.dom");
    dojo.require("dojo.parser");
    dojo.require("dijit.form.Slider");
    if (evt) {
        var searchUrl = evt.target.href + '/ajax';
    }
    else if (window.location.hash) {
        var searchUrl = 'http://' + window.location.hostname + '/' + window.location.hash.replace('#', '') + '/ajax';
        
    }
    // Call the productFinder
    dojo.xhrGet({
        url: searchUrl,
        handleAs: "text",
        handle: productFinderCb
    });
}

/**
 * Callback function for rendring the product finder within page.
 * Adds some custom stylesheets, elems and javascripts.
 *
 */
function productFinderCb(response, ioArgs) {
    // Set document body as container and document head as head
    var body = document.body;
    var container = document.createDocumentFragment();
    var head = dojo.query("head")[0];
    
    // Load the productFinder javascript
    var productFinderJS = document.createElement("script");
    productFinderJS.type = "text/javascript";
    productFinderJS.src = "/js/productfinder.js?" + forceReload();
    productFinderJS.className = "productFinderStatic";
    head.appendChild(productFinderJS);

    // Hide all ads in the wrapper
    dojo.query("#wrapper .ads").forEach(function(item) {
        dojo.style(item, "visibility", "hidden");
    });

    // Append needed productFinder stylesheets
    var stylesheets = [
        'http://static.new.gfx.no/css/productfinder.css',
        '/js/dijit/themes/tundra/tundra.css',
        '/js/dojo/resources/dojo.css'
    ];
    dojo.forEach(stylesheets, function(sheet) {
        var cssLink = document.createElement("link");
        cssLink.href = sheet;
        cssLink.type = "text/css";
        cssLink.rel = "stylesheet";
        dojo.addClass(cssLink, "productFinderStatic");
        head.appendChild(cssLink);
    });

    // Create overlay div
    var overlay = document.createElement("div");
    dojo.addClass(overlay, "overlay");

    // IE doesn't support position: fixed, so give it a absolute position
    if (dojo.isIE == 6) {
        dojo.query("html, body").forEach(function(item) {
            dojo.style(item, "height", "100%");
        });
    }

    // Create productFinder container
    var productFinder = document.createElement("div");

    // Run TNS
    getTMqs('http', '', '', 'hardware_no_orklamedia_no', 'no', 'ISO-8859-15');

    dojo.addClass(productFinder, "productFinderHolder");
    // TODO: Move styles to stylesheets
    dojo.style(productFinder, {
        "border": "3px solid #000",
        textAlign: "left",
        "width": "996px",
        "position": "absolute",
        "top": "50px",
        "left": "50%",
        "margin": "0 0 0 -498px",
        "background": "#fff",
        zIndex: 200
    });

    // Load the ajax response in to the productFinder container and add close button
    productFinder.innerHTML = response;
    var buttonClose = document.createElement("a");
    buttonClose.href = "#";
    dojo.addClass(buttonClose, "close");
    buttonClose.appendChild(document.createTextNode("Lukk vindu"));
    dojo.connect(buttonClose, "onclick", closeProductFinder);
 
    // Parse product finder so we can load the dijit sliders
    dojo.parser.parse(productFinder);
    
    // Append all new elements and the destroy the loading icon
    productFinder.appendChild(buttonClose);
    container.appendChild(overlay);
    container.appendChild(productFinder);
    body.appendChild(container);

    if (dojo.query("body img.loading")) {
        dojo.query("body img.loading").forEach(function(item) {
            dojo._destroyElement(item);
        });
    }
}

/**
 * Callback-function for closing the product finder-popup.
 * Removes custom stylesheets, elements and javascripts.
 *
 */
function closeProductFinder(evt) {
    if (evt)
        evt.preventDefault();

    // Find product finder and overlay
    var productFinder = dojo.query(".productFinderHolder")[0];
    var overlay = dojo.query(".overlay")[0];
    
    // Destroy dijit slider widgets so we can load the product finder once more without reloading page
    dojo.query(".productFinderHolder .dijitSlider").forEach(function(tag) {
        dijit.byId(tag.id).destroy();
    });

    // Lets show the ads again
    dojo.query("#wrapper .ads").forEach(function(item) {
        dojo.style(item, "visibility", "visible");
    });

    // Remove custom stylesheets
    dojo.query("head .productFinderStatic").forEach(function(item) {
        dojo._destroyElement(item);
    });

    // Fade out and destroy product finder
    var productFinderFadeOut = dojo.fadeOut({
        node: productFinder,
        duration: 500
    }).play();
    dojo.connect(productFinderFadeOut, 'onEnd', function() {
        dojo._destroyElement(productFinder);
    });

    // Fade out and destroy overlay
    var overlayFadeOut = dojo.fadeOut({
        node: overlay,
        duration: 500
    }).play();
    dojo.connect(overlayFadeOut, 'onEnd', function() {
        dojo._destroyElement(overlay);
    });

    // We have to reload zeh css if browser is running the Webkit framework and IE, beacuse it will not reload back to it's old self again
    if (dojo.isSafari || dojo.isIE) {
        dojo.query("head link[rel='stylesheet']").forEach(function(link) {
            var h = link.href.replace(/(&|\\?)forceReload=d /,'');
            link.href = h + (h.indexOf('?') >= 0 ? '&' : '?') + 'forceReload=' + forceReload();
        });
    }
    
}

function forceReload() {
    return (new Date().valueOf());
}

dojo.addOnLoad(addOnEvents);
dojo.addOnLoad(addGoto);
