/**
 * @author Fahrettin Kutyol
 * This is the rebuilt for dojo 1.2.x of the former 0.4 shopdialog widget.
 * This widget had to be coded from scratch, because the fundamental design of widgets
 * had been changed since dojo 0.9.x. Unlike to the old version this widget doesn't extend
 * a tooltip widget.
 * Some variables were taken over from the former widget to guarantee compatiblility to
 * the template calls
 *
 * this widget contains improvements in the visual presentation.
 * e.g. a waiting image has been added, the background fades in and the whole dialog fades out.
 * but depending to the requirements of the template calls this is work around like.
 * that means, it's not a decent rebuilt because some individual functions of the
 * former widget had to be taken over and refactored.
 *
 * !! the whole design of the dialog structure and calling of the dialogs should be reconsidered !!
 *
 *  Dependencies:
 *  the shopdialog widget is not called like all other widgets by connecting to a node of the
 *  template with djConfig. this widgets is called once in the file
 *  HaufePortal/skins/Infrastruktur/main_template.js
 *  all dialog calls are using explodeLayer() and implodeLayer()
 *
 * To do:
 * in the former widget there are some form handling functions. check if this is needed.
 * jsonProcess is a function of the old widget and have been used to validate json data.
 * but some calls didn't do what they have to do, also in the old version.
 * so this function also should be reconsidered.
 *
 *  Summary:
 *  This a modulated dialog widgets ecpecially for haufe ep needs and visual design.
 *
 *
 */
dojo.provide("haufedojo.widget.shopdialog");

var haufedojoDialogInstance = undefined;

// requirering the refactored widget superclass
dojo.require("haufedojohelp.data.HaufeUtils");
dojo.require("dijit.z_Widget");
dojo.require("dijit.z_Templated");


//building the widget class
dojo.declare("haufedojo.widget.shopdialog", //our subclass
 [dijit.z_Widget, dijit.z_Templated], // superclasses
{
    href: "", // url of the content or the a dojo xhrArg see: http://docs.dojocampus.org/dojo/xhrGet
    bgIframe: null, // background iframe
    cssImported: false, // check if the css already have been imported
    dlg_position_x: "center", // position of the dialog
    dlg_x: "undefined", // adding x px to the position x
    dlg_width: 0, // width of the dialog
    dlg_height: 0, // height of the dialog
    jsParams: {}, // javascript parameters
    scrollfoff: true, // switch scroll on/off of the dialog
    isAlive: "undefined", // is this a new object or an already existing
    totalImages: 0, // total count of the images in the content to wait for them
    countImages: 0, // counting the images on load
    bgAnimateOpacity: 0, // opacity of the bg fading
    isShowing: false, // does the dialog show
    waitingImage: null, // node of the waiting image
    timeout: 16000, // time until XHR request gets aborted
    templatePath: "/haufedojo/widget/templates/shopdialog.html",
    // called after creation
    postCreate: function() {
        // By the first call we need to load the css and create haufeUtils
        this.haufeUtils = new haufedojohelp.data.HaufeUtils();
        if (!this.cssImported) {
            this.importCss("haufedojo/widget/templates/shopdialog.css");
        }
        // Setting the styles of the dom node.
        ds = this.domNode.style;
        ds.position = "absolute";
        ds.display = "block";
        ds.zIndex = "103";

        // shadow box (just behind dialog box, but with slightly offset to give visual effect of a shadow)
        // got this from the former version.
        this.boxShadow = document.createElement("div");
        this.boxShadow.className = "haufedojoShadow";
        this.boxShadow.id = "boxShadow";
        var inner = "<div class='rBoxShadow'><span class='rBoxTop'><span class='rBox1'></span><span class='rBox2'></span><span class='rBox4'>";
        inner += "<span class='rBoxCenterTop'></span></span></span><div class='rBoxOuterBox'><div class='rBoxInnerBox' id='innerShadowBox'>";
        inner += "</div></div><span class='rBoxBottom'><span class='rBox4'><span class='rBoxCenterBottom'></span></span>";
        inner += "<span class='rBox2'></span><span class='rBox1'></span></span></div>";
        this.boxShadow.innerHTML = inner;
        // Setting the box shadow styles
        //dojo._setOpacity(this.boxShadow, 0.4);

        // setting up a waiting image
        this.waitingImage = document.createElement("img");
        this.waitingImage.setAttribute("src","haufedojo/widget/templates/images/waiting.gif");
        this.waitingImage.setAttribute("border","0");
        this.waitingImage.className = "haufeDialogWaitingImage"

        if (this.scrolloff) {
            this.domNode.style.overflowX = "hidden";
            this.domNode.style.overflowY = "hidden"; //"auto", "visible", "scroll"
        }
        this.bg = document.createElement("div");
        this.bg.id = "shopdialogBg";
        this.bg.className = "haufeDialogUnderlay";
        //dojo._setOpacity(this.bg, 0)
        // We only append the nodes to the body by the first call
        var b = dojo.body();
        b.appendChild(this.bg);
        b.appendChild(this.waitingImage);
        b.appendChild(this.boxShadow);
        b.appendChild(this.domNode);
        this.connect(window,"onresize","windowResize")
        // this is a flag to detect if this object has already been created
        this.isAlive = true;
    },
    // Loading content and initalize the dialog
    initContent: function(){
        // we need to set the parameters for image handling to zero.
        this.totalImages = 0;
        this.countImages = 0;

        if(typeof this.href == "string") {
            var xhrArgs = {
                url: this.href,
                timeout: this.timeout
            }
        } else {
            var xhrArgs = this.href
            if(typeof xhrArgs.timeout == "undefined")
                xhrArgs.timeout = this.timeout
        }
        xhrArgs.load = dojo.hitch(this,"callback")
        xhrArgs.error = dojo.hitch(this,"callbackError")
        if(typeof xhrArgs.form == "undefined")
            dojo.xhrGet(xhrArgs);
        else
            dojo.xhrPost(xhrArgs)
    },
    callback : function(response, ioArgs){
        // Check if response is json data
        var jsonData = undefined;
        try {
            jsonData = dojo.fromJson(response);
        }catch(e){
            console.debug("No JSON Data");
        }
        var proceed = true;
        if (jsonData) {
            console.debug("JSON DATA DETECTED!");
            proceed = this.jsonProcess(jsonData);
        }
        if(proceed){
            // No JSON data or jsonProcess = true means to output the response in to the dialog
            this.containerNode.innerHTML = response;
            // Check if the response contains javscript code and put it to the head
            this.scriptEval(this.containerNode);
            // Adding onLoad-count-handlers to the images.
            // Need to wait until all images have been loaded.
            // Otherwise we won't get the right height.
            var imagesArray = this.containerNode.getElementsByTagName("img");
            this.totalImages = imagesArray.length;
            if (this.totalImages != 0) {
                dojo.forEach(imagesArray, dojo.hitch(this, function(item){
                    item.onload = dojo.hitch(this, this.imageLoaded);
                    // Be sure to display the layover even if some of the images cannot be loaded
                    item.onerror = dojo.hitch(this, this.imageLoaded);
                    item.onabort = dojo.hitch(this, this.imageLoaded);
                }));
            } else {
                this.displayContent(); // no images so display it directly
            }
        }
    },
    callbackError: function(response, ioArgs)
    {
        this.containerNode.innerHTML ="<center>" +
        "<h3 class='dialogError'>W&aumlhrend der Verarbeitung Ihrer Anfrage ist ein Fehler aufgetreten.</h3></center>"
        this.displayContent();
        console.debug("Failed XHR: ", response, ioArgs);
    },
    // function that is fired by each onload of an image inside the dialog
    imageLoaded: function(){
        // An Images has been loaded. We increase the size of counted Images
        this.countImages++;
        // We compare to the total amount of images that has to be loaded.
        // if the count of the images match the total amount we fire the adjust function
        if (this.totalImages == this.countImages) {
            this.displayContent();
        }
    },
    displayContent : function(){
        var ds = this.domNode.style;
        var bs = this.boxShadow.style;
        ds.visibility = "hidden";
        bs.visibility = "hidden";
        ds.display = "block";
        bs.display = "block";
        this.waitingImage.style.display = "none";
        // Show the dialog
        this.isShowing = true;
        this.adjust();
        window.setTimeout(dojo.hitch(this,this.phasedRenderer) ,0) // 0ms is just enough to ensure a correct rendering
    },
    // Size calculation are usually inconsistent just after appending content into the DOM
    phasedRenderer : function(){
        this.adjust()
        var ds = this.domNode.style;
        var bs = this.boxShadow.style;
        ds.visibility = "visible";
        bs.visibility = "visible";
        dojo._setOpacity(this.domNode,1);
        dojo._setOpacity(this.boxShadow,0.4);
    },
    // parsing all javscript code 
    scriptEval: function(node){
        var scriptArray = node.getElementsByTagName("script");
        var totalScripts = scriptArray.length;
        if (totalScripts!= 0) {
            var head = document.getElementsByTagName("head")[0];
            for(var i=0; i < totalScripts; i++){
                var item = scriptArray[i]              
                // Getting all signs out that would disturb IE
                var jscall = item.innerHTML.replace(/<!--/g,'').replace(/\/\/-->/,'').replace(/^\s*([\S\s]*?)\s*$/, '$1')
                dojo.eval(jscall)
            }
        }
    },
    // Internal widget css requirement doesn't exist anymore in dojo 1.x
    // This is a hack to import a css file
    importCss: function(fileName){
        var fileref = document.createElement("link");
        fileref.setAttribute("rel", "stylesheet");
        fileref.setAttribute("type", "text/css");
        fileref.setAttribute("href", fileName);
        if (typeof fileref != "undefined")
            document.getElementsByTagName("head")[0].appendChild(fileref);
        this.cssImorted = true;
    },
    // Showing the dialog
    show: function(){
        dojo._setOpacity(this.domNode,0);
        dojo._setOpacity(this.boxShadow,0);
        this.waitingImage.style.display = "block";
        this.initContent();
        if(!this.isShowing) {
            window.scrollTo(0, 0);
            window.setTimeout(dojo.hitch(this,this.phasedBGRenderer) ,0) // 0ms is just enough to ensure a correct rendering
            if(this.bgIframe) {
                this.bgIframe.iframe.style.display = "block";
            }

        }
    },
    phasedBGRenderer: function(){
        this.adjustBackground();
        this.adjustLoadingImg();
        this.bg.style.display = "block";
        //dojo.fadeIn({node:this.bg}).play();
        this.bgFadeIn();
    },
    // Hiding the dialog
    hide: function(){
        this.dFadeOut();
        this.bgFadeOut();
    },
    
    hideAndDestroy: function() {
    	this.hide();
        window.setTimeout(dojo.hitch(this, function() {
        	this.setContent("");
        	this.destroy();
        }),500);
//    	var combinedFading = dojo.fx.chain([
//        this.dFadeOut(),
//        this.bgFadeOut()]);
//    	dojo.connect(combinedFading,"onEnd", function() {alert("ok")})
//    	combinedFading.play();
    },
    
    adjustLoadingImg: function() {
        var ws = this.waitingImage.style;
        var viewport = dijit.getViewport();
        var l = ((viewport.w - 128)/2) + viewport.l;
        var t = ((viewport.h - 128)/2) + viewport.t;
        ws.left = l + "px";
        ws.top = t + "px";
    },
    // creating the background in front of the site but behind the dialog
    // Some parts have been ripped and refactored for 1.2.x from the old shopdialog widget
    adjustBackground: function() {
        // Create it if it does nit exsist
        // Getting the real height of the page
        if(window.innerHeight && window.scrollMaxY) {// Firefox
            yWithScroll = window.innerHeight + window.scrollMaxY;
            //xWithScroll = window.innerWidth + window.scrollMaxX;
        }
        else if(document.body.scrollHeight > document.body.offsetHeight) { // all but Explorer Mac
            yWithScroll = document.body.scrollHeight;
            //xWithScroll = document.body.scrollWidth;
        }
        else { // works in Explorer 6 Strict, Mozilla (not FF) and Safari
            yWithScroll = document.body.offsetHeight;
            //xWithScroll = document.body.offsetWidth;
        }

        // setting the styles of the background
        var viewport = dijit.getViewport();
        this.bg.style.width = viewport.w + "px";
        this.bg.style.height = yWithScroll + "px";
        if (this.bgIframe) {
            this.bgIframe = new dijit.BackgroundIframe(this.bg);
        }
    },
    // Background fade in
    bgFadeIn: function(){
        dojo.animateProperty({
            node: this.bg,
            duration: 200,
            properties: {
                opacity: 0.6
            },
            onPlay: dojo.hitch(this, function(){
                this.domNode.style.visibilty = "hidden";
                this.boxShadow.style.visiblity = "hidden";
                this.boxShadow.style.display = "none";
                this.bg.style.display = "block";
                if(this.bgIframe) {
                    this.bgIframe.iframe.style.display = "block";
                }
            })
        }).play();
    },
    // Background fade out
    bgFadeOut: function(){
        dojo.animateProperty({
            node: this.bg,
            duration: 200,
            properties: {
                opacity: 0
            },
            onEnd: dojo.hitch(this, function(){
                this.bg.style.display = "none";
                if (this.bgIframe) {
                    this.bgIframe.iframe.style.display = "none";
                }
            })
        }).play();
    },
    // Fading out the dialog. looks better.
    // didn't used a dialog fade in. this might cause problems
    dFadeOut: function(){
        var ds = this.domNode.style;
        var bs = this.boxShadow.style;
        ds.visibility = "visible";
        bs.visibility = "visible";
        dojo.fadeOut({
            node: this.domNode,
            onEnd: dojo.hitch(this,function(){
                this.domNode.style.display = "none";
                this.isShowing = false;
            })
        }).play();
        dojo.fadeOut({
            node: this.boxShadow,
            onEnd: dojo.hitch(this,function(){
                this.boxShadow.style.display = "none";
            })
        }).play();

    },
    // Ripped and refactored for 1.2.x from the old shopdialog widget
    // Setting the right bounds for dialog window and underlying shadow box.
    adjust: function(){
        var viewport = dijit.getViewport();
        var bounds = dojo.coords(this.domNode, false);
        var x = 0;
        var y = 0;
        var w = 0;
        var h = 0;
        /*MyFrame will nen Scrollbalken*/
        if (bounds.h > 350) {
            var portletChangeScroll = dojo.query(".portletChangeScroll");
            if (portletChangeScroll.length) { /*Is it really the myframe dialog*/
                var portletChangeStyle = portletChangeScroll[0];
                dojo.style(portletChangeStyle, {
                    "overflowY": "scroll",
                    "overflowX": "hidden",
                    "height": "250px"});
            }
        }
        y = Math.round((viewport.h - bounds.h) / 2);
        if(y < 30)
            y = 30
        // horizontal adjusting
        switch (this.dlg_position_x) {
            case "center":
                if (bounds.w >= viewport.w) {
                    x = viewport.l;
                }
                else {
                    x = viewport.l + (viewport.w - bounds.w) / 2;
                }
                w = 0;
                break;

            case "absolute":
                x = viewport.l + this.dlg_x;
                break;
            /*dlg_width shoud be 0*/
            case "relative":
                w = (viewport.w * this.dlg_width) / 100;
                x = viewport.l + (viewport.w - w) / 2;
                break;

            default:
                w = 500;
                x = 200;
                break;
        }
        if (this.dlg_width === 0) {
            if (mb.w >= viewport.w) {
                x = viewport.l;
            }
            else {
                x = viewport.l + (viewport.w - bounds.w) / 2;
            }
            w = 0;
        }
        else {
            w = this.dlg_width;
            x = viewport.l + (viewport.w - w) / 2;
        }

        //var screenArr = dojo.query("div.screenshot");
        this.haufeUtils.widenDomain();
        //if (screenArr.length && (document.domain === "wrs.de" || document.domain === "haufe.de")) {
        //    y = 60;
        //}

        h = bounds.h;

        var ds = this.domNode.style;
        ds.left = x + "px";
        ds.top = y + "px";
        if (w !== 0) {
            ds.width = w + "px";
        }
        //adjust shadow
        var bss = this.boxShadow.style;
        bss.left = (x + 4) + "px";
        bss.width = w + "px"; // ds.width
        // IE7 Bug : shadowBox height has to to come from inside
        bss.top = (y + 4) + "px";
        // IE7 Bug : return NaN if any opertions on mb.height are beeing executated inline
        var bssHeight = h - 6;
        if (bssHeight > 0) {
            dojo.byId("innerShadowBox").style.height = bssHeight + "px";
        }
    },
    // can be deleted
    setContent: function(content){
        this.containerNode.innerHTML = content;
    },

    windowResize: function(evt) {
        this.adjustBackground();
        this.adjustLoadingImg();
        this.adjust();
    },
    // ripped and refactored from the old version
    // return true if you want to fill the response to the dialog
    // return false if you don't want to fill the response to the dialog
    // CAUTION: it is strongly recommended to reconsider this function.
    jsonProcess: function(jsonData){
        console.debug("jsonProcess: " + jsonData.url + " jsonData.pc_action: " + jsonData.pc_action +  "jsonData.layover: " + jsonData.layover);

        if (jsonData.pc_action == "forceRedirectHttps") {
            console.debug("jsonProcess ==> forceRedirctHttps");
            dojo.body().style.cursor = "progress";//"url('/loadingImageSmall')";
            var content = '<div id="page"><div class="contentProcess"><h1>Weiterleitung</h1><hr class="defaultSubline"/><br/><br/>Bitte warten.';
            content += '<hr class="defaultSubline"/></div></div>';

            this.setContent(content);
            setTimeout( function redi(){
                window.location.href = jsonData.url;
            }, 2500);
            return false;
        }
        else
            if (jsonData.pc_action == "forceRedirect") {
                console.debug("jsonProcess ==> forceRedirctHttp");
                this.setContent("");
                this.hide();
                window.location.href = jsonData.url;
                 return false;
            }
            else
                if (jsonData.pc_action == "formConnect" || jsonData.layover == "notLayoverRelo") {
                    console.debug("jsonProcess ==> formConnect or notLayoverRelo");
                    //this.formEventConnect(jsonData.formAvailable);
                     return true;
                }
                else
                    if (jsonData.layover) {
                        if (jsonData.layover == "layover") {
                            console.debug("jsonProcess ==> layover");
                            var content = '<div id="page"><div class="contentProcess"><h1>Weiterleitung</h1><hr class="defaultSubline"/><br/><br/>Bitte warten.';
                            content += '<hr class="defaultSubline"/></div></div>';
                            this.containerNode.innerHTML = content;
                            this.adjust();
                            window.location.href = jsonData.url;
                            return false;
                        }
                        else
                            if (jsonData.layover == "notLayover") {
                                console.debug("jsonProcess ==> notLayover");
                                this.setContent("");
                                this.hide();
                                jsonData.layover = "notLayoverRelo";
                                window.location.href = jsonData.url + '?explodeLayerUrl=' + dojo.formToJson(jsonData);
                                return false;
                            }
                    }
                    else {
                        console.debug("jsonProcess ==> NO SPECIFIC ORDER");
                        window.location.href = jsonData.url;
                        return true;
                    }
     console.debug("NO JSON VARIABLES");
     return true;
    }
});

