﻿// The URL to the root of the quebles site.
var WEBSITE_ROOT_URL = new String("http://www.quebles.com");

// NB.: This file depends on the cvi_reflex_lib.js file!!

function ProductPreview(containerElementId, contentType, productId, descriptionText, buttonText) {
    var moods;					// Will contain DDP moods    
    var ddpMoodImageLocation;  
    var initialPreview = true;  
    
    this.containerElementId = containerElementId;
    this.contentType = contentType;
    this.productId = productId;
    this.descriptionText = descriptionText;
    this.buttonText = buttonText;
    //
    // Public Methods
    //
    this.ShowPreview = function(productId, contentType) {
        this.productId = productId;
        this.contentType = contentType;

        var element = document.getElementById(this.containerElementId);

        // Make sure we could reference required container element
        if (element) {
            element.innerHTML = BuildPreviewHtml(this.contentType, this.productId);

            // If DDP show mood preview links
            if (contentType == 42) { this.ShowMoodsPreview(productId); }

            // Set the preview image with the reflection if not initial preview (first time after page load).
            if (!initialPreview) {
                var reflectImage = document.getElementById("imgPreview");
                if (reflectImage) { cvi_reflex.add(reflectImage, ""); }
            }
            else {
                initialPreview = false;
            }
        }
    };    
    this.ShowMood = function(mood) {
        var container = document.getElementById(this.containerElementId);
        
        if (container) {			
			// IE needs a different implementation as it does not support EMBED tag.			
			if (IsIE()) {
				var previewIFrame = document.getElementById("PreviewIFrame");				
				var swfSourceUrl = new String(previewIFrame.getAttribute("src"));
				var swfTargetUrl = swfSourceUrl.substr(0, swfSourceUrl.indexOf("?")) + "?" + moods[mood].GetMoodName();						
				
				window.frames["PreviewIFrame"].location = WEBSITE_ROOT_URL + "/images/flashpreview.ashx?t=d&p=" + this.productId + "&m=" + escape(moods[mood].GetMoodName());
			}
			else {
				var url = null;
				var movieElement = null;
				var obj = document.getElementById("Preview");
				var embed = document.getElementById("DDPMoodPreviewEMBED");	
				
				for	(var i = 0; i < obj.childNodes.length; i++) {				
					if (obj.childNodes.item(i).getAttribute("name") == "movie") {
						movieElement = obj.childNodes.item(i);
						break;
					}
				}
				
				// Get container's current HTML
				var html = new String(container.innerHTML);
	
				// Reference the EMBED element to get the SWF url and append our new mood parameter
				var embed = document.getElementById("DDPMoodPreviewEMBED");
				var swfSourceUrl = new String(embed.getAttribute("src"));
				var swfTargetUrl = swfSourceUrl.substr(0, swfSourceUrl.indexOf("?")) + "?" + moods[mood].GetMoodName();
	            
				// create new HTML for container by replacing the URL's and set containers HTML.            
				var newHtml = html.replace(swfSourceUrl, swfTargetUrl).replace(swfSourceUrl, swfTargetUrl);
				container.innerHTML = newHtml;
			}
        }  
    };        
    this.ShowDefaultPreview = function() {
        var product = GetFirstProduct();
        this.ShowPreview(GetProductId(product), GetProductCategory(product));    
    };
    this.ShowMoodsPreview = function(productId) {
        var url = WEBSITE_ROOT_URL + "/AjaxService.ashx?action=moods&product=" + productId + "&language=nl";
        var moodPreviewContainer = document.getElementById("PreviewDDPMoods");

        if (moodPreviewContainer) { moodPreviewContainer.innerHTML = "<img src=\"" + WEBSITE_ROOT_URL + "/images/ajax-loader.gif\" />"; }

        new Ajax.Request(url, {
            method: 'get',
            onSuccess: function(transport) {
                var response = transport.responseText;
                var separator = "$Preview.Separate$";
                var responseLines = response.split("\n");
                var parts;

                if (moodPreviewContainer) {
                    // Create an empty array to contain the moods.
                    moods = new Array();

                    // each response line is splitted into array ([0] == mood [1] == key [2] == text)
                    // we get an additional blank line so iterate till (length - 1)
                    for (var i = 0; i < responseLines.length; i++) {
                        // Split into an array of parts
                        parts = responseLines[i].split(separator);

                        // Make sure we have all values required for a mood                        
                        if (parts[0] != "" && parts[1] != "" && parts[2] != "") {
                            moods.push(new Mood(parts[0], parts[1], parts[2]));
                        }
                    }

                    // Now build preview html and show it to user.
                    var previewHtml = "";
                    for (var j = 0; j < moods.length; j++) {
                        previewHtml += "<a href=\"javascript:Preview.ShowMood(" + j + ");\">";
                        previewHtml += moods[j].ToHtmlString();
                        previewHtml += "</a>";
                    }

                    moodPreviewContainer.innerHTML = previewHtml;
                }
            },
            onException: function(requester, exception) {
                if (moodPreviewContainer) { moodPreviewContainer.innerHTML = ""; }
            },
            onFailure: function(transport) {
                if (moodPreviewContainer) { moodPreviewContainer.innerHTML = ""; }
            }
        });
    };
    function IsFlash(contentType) {
        return  contentType == 42 || contentType == 43;
    };    
    function FlashScript(swfUrl, width, height, contentType) {
		var script = null;
    
        // Set required <EMBED> elment ID for DDP mood preview
        var embedId = "";
        if (contentType == 42) { embedId = "id=\"DDPMoodPreviewEMBED\""; }        
        
        // For IE we need to use an IFRAME as otherwise we can't activate the moods dynamically.
        if (IsIE()) {        
			script ="<iframe id=\"PreviewIFrame\" frameborder=\"0\" src=\"" + swfUrl + "\" width=\"" + (contentType == 42 ? "98" : "180") +"\" height=\"" + (contentType == 42 ? "142" : "180") +"\"></iframe>";
        }
        else {        
			script = "<object classid=\"clsid:d27cdb6e-ae6d-11cf-96b8-444553540000\" codebase=\"http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0\" width=\"" + width + "\" height=\"" + height + "\" id=\"Preview\" align=\"middle\" VIEWASTEXT>";
			script += "<param name=\"allowScriptAccess\" value=\"always\" />";
			script += "<param name=\"movie\" value=\"" + swfUrl + "\" />";        
			script += "<param name=\"quality\" value=\"high\" /><param name=\"bgcolor\" value=\"{0}\" />";      
			script += "<embed " + embedId + " src=\"" + swfUrl + "\" quality=\"high\" bgcolor=\"{0}\" width=\"" + width + "\" height=\"" + height + "\" name=\"Preview\" align=\"middle\" allowScriptAccess=\"always\" type=\"application/x-shockwave-flash\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\" />";
			script += "</object>";
		}
        
        // Add additional html to display DDP background image and set the flash movie object
        // background color by replacing the {0} placeholder with a proper value.
        if (contentType == 42) {     
            return new String("<div id=\"PreviewDDP\">" + script + "<div id=\"PreviewDDPMoods\"></div></div>").replace(/\{0\}/g, "#333333");
        }
        else {
            return new String(script).replace(/\{0\}/g, "#FFFFFF");            
        }
    };    
    function GetPreviewFile(type, productId) {
        var commonLocation = "http://preview.mobilemoney.com/content/";
        
        // Cast type to number otherwise it may not work
        switch(Number(type)) {
            case 30: return commonLocation + "emoticons/preview/80x80/" + productId + ".gif";
            case 31: return commonLocation + "dp/preview/80x80/" + productId + ".jpg";            
            case 42: 
				if (IsIE()) {
					return WEBSITE_ROOT_URL + "/images/flashpreview.ashx?t=d&p=" + productId;
				} 
				else {
					return commonLocation + "ddp/preview/full/" + productId + ".swf?themood=standaard";
				}
            case 43: 
				if (IsIE()) {
					return WEBSITE_ROOT_URL + "/images/flashpreview.ashx?t=w&p=" + productId;
				} 
				else {
					return commonLocation + "winks/preview/" + productId + ".swf";
				}
            case 44: return commonLocation + "backgrounds/preview/80x80/" + productId + ".jpg";
            case 45: return commonLocation + "themes/preview/80x80/" + productId + ".jpg";
        }
        return "";
    };    
    function BuildPreviewHtml(contentType, productId) {
        var str = "";
        
        // Add preview image or flash
        str += "<div id=\"Image\" class=\"content" + contentType + "\">";
        if (IsFlash(contentType)) {
            // DDP preview
            if (contentType == 42) {
                str += FlashScript(GetPreviewFile(contentType, productId), 98, 142, contentType);
            }
            else {  // Wink preview                
                str += FlashScript(GetPreviewFile(contentType, productId), 180, 180, contentType);
            }
        }
        else {        
            str += "<img src=\"" + GetPreviewFile(contentType, productId) + "\"";
            if (contentType == 30 || contentType == 31 || contentType == 44 || contentType == 45) {
                str += " class=\"static reflex itiltnone\"";
            }
            str += "alt=\"Preview\" id=\"imgPreview\" />";           
        }
        str += "</div>";
        
        // Add description
        str += "<div id=\"Description\">";
		if (descriptionText.length > 2) str += "<p>" + descriptionText + "</p>";
		
		// If theme pack we need to add theme pack details. 
        if (contentType == 45) { 
			str += "<div id=\"ThemePackDetails\"></div>";
			GetThemePackDetailsHtml(productId);

			str += "[ORDERBUTTON]";
		}
		
		str += "</div>";
        
		// Add price
		str += "<div id=\"Price\">";		
		str += "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
		str += "</div>";
		//str += "<a href=\"../order.aspx?product=" + productId + "&cat=" + contentType + ">" + buttonText + "</a>";		
		
		// Show the ORDER button if a text for the button was set.
		if (buttonText != null) {
		    if (contentType == 45) {
		        str = str.replace("[ORDERBUTTON]", "<div id=\"Button\"><input style=\"margin-left: 0 !important;\" type=\"button\" value=\"" + buttonText + "\" onclick=\"window.location.href = '../order.aspx?product=" + productId + "&cat=" + contentType + "';\" /></div>");
		    }
		    else {
		        str += "<div id=\"Button\"><input type=\"button\" value=\"" + buttonText + "\" onclick=\"window.location.href = '../order.aspx?product=" + productId + "&cat=" + contentType + "';\" /></div>";
		    }
		}
		else {
			// Otherwise don't show a button but just an empty P-tag.
			str += "<p style=\"margin:6px 0pt 0pt 6px;\">&nbsp;&nbsp;</p>";
			
			// We need to set height of PreviewContainer DIV to 184px so the preview is displayed correctly during order process.
			if (contentType == 42) {
				var container = document.getElementById("PreviewContainer");				
				if (container) container.setAttribute("style", "height: 184px !important;");
			}
		}
		        
        return str;
    };
    function GetFirstProduct() {
        var elem = document.getElementById("WizardContent");       
        
        // Reference the wizard html output containing div
        if (elem) {
            // Reference all DIVs within it as they represent the products
            var products = elem.getElementsByTagName("div");            
            if (products && products.length > 0) {
                // Get first product and reference the A tag within 
                return products[0]; 
            }
        }
        return null;    
    };
    function GetProductId(product) {               
        if (product) {                    
            var anchor = product.getElementsByTagName("a")[0];         
            if (anchor) {                        
                // Get the href attribute value
                var href = new String(anchor.getAttribute("href"));                        
                return href.substring(href.indexOf("Preview.ShowPreview(") + 20, href.indexOf(","));
            }
        }      
        return 0;
    };
    function GetProductCategory(product) {              
        if (product) {                    
            var anchor = product.getElementsByTagName("a")[0];         
            if (anchor) {                        
                // Get the href attribute value
                var href = new String(anchor.getAttribute("href"));  
                var begin = new String(href.substr(0, href.indexOf(", ")));                                      
                return Number(href.substring(begin.length + 2, href.indexOf(")")));
            }
        }          
        return 0;
    };
    
    function GetThemePackDetailsHtml(productId) {
		var url = WEBSITE_ROOT_URL + "/AjaxService.ashx?action=packdetails&product=" + productId + "&language=nl&rnd=" + Math.random();				
		var errorMessage = "Unable to fetch theme pack details. Please refresh the page and try again.";
		var html = "";

		new Ajax.Request(url, {
		    method: 'get',
		    onSuccess: function(transport) {
		        var response = new String(transport.responseText);
		        var parts = response.split("|");

		        if (Number(parts[0]) != 0) { html += parts[0] + " emoticons <br/>"; }
		        if (Number(parts[1]) != 0) { html += parts[1] + " display picture <br/>"; }
		        if (Number(parts[2]) != 0) { html += parts[2] + " wink <br/>"; }
		        if (Number(parts[3]) != 0) { html += parts[3] + " DDP <br/>"; }
		        if (Number(parts[4]) != 0) { html += parts[4] + " backgrounds <br/>"; }
		        if (Number(parts[5]) != 0) { html += parts[5] + " dynamic backgrounds <br/>"; }

		        document.getElementById("ThemePackDetails").innerHTML = html;
		    },
		    onException: function(requester, exception) {
		        document.getElementById("ThemePackDetails").innerHTML = errorMessage;
		    },
		    onFailure: function(transport) {
		        document.getElementById("ThemePackDetails").innerHTML = errorMessage;
		    }
		}); 
    };
    
    function IsIE() {
		return window.navigator.userAgent.indexOf("MSIE ") > 0;
	};
}

//
// Mood Class. Represents a Mood in a DDP.
//
function Mood(name, key, text) {
    this.name = name;
    this.key = key;
    this.text = text;
    //
    // Returns an HTML representation of the mood.
    //
    this.ToHtmlString = function() {
        if (this.key != "" && this.key != null) {      
            return "<img src=\"" + WEBSITE_ROOT_URL + "/images/icons/" + GetKeyStrokeImage(GetKey(this.key)) + "\" border=\"0\" width=\"19\" height=\"19\" alt=\"" + this.text + "\" title=\"" + this.text + "\" />";       
        }
        else {
            return "";
        }
    };  
    
    this.toString = function() {
        return "Mood parameter: " + this.name + ", key: " + this.key + ", text: " + this.text;
    };
    //
    // Returns the moodname.
    // 
    this.GetMoodName = function() {
        return this.name;
    };


    this.GetImageSrc = function() {
        return WEBSITE_ROOT_URL + "/images/icons/" + GetKeyStrokeImage(GetKey(this.key));
    };
    //
    // Gets the first key (if more than one specified) of the keys value.
    //
    function GetKey(keys) {
        if (keys.indexOf("\t") > 0) {
            var keyParts = new String(keys).toLowerCase().split("\t");        
            return keyParts[0];
        }
        else {
            return keys.toLowerCase();
        }   
    }; 
    //    
    // Returns the image associated with the specified keystroke.
    //
    function GetKeyStrokeImage(key) {        
        switch(key) {           
            case ":-d":
            case ":d":  return "laugh.png";
            case ":-)":
            case ":)":  return "smile.png";
            case ";-)":
            case ";)":  return "wink.png";            
            case ":-@": 
            case ":@":
            case "8o|": return "angry.png";	
            case ":(":
            case ":-(": return "sad.png";
            case ":'(": return "crying.png";            
            case ":-|": 
            case ":|":
            case "(n)": return "sad.png";
            case ":-o":
            case ":o":  return "surprised.png";            
            case ":-p":            
            case ":p":  return "tongue.png";          
            case "(k)": return "kiss.png";
            case "(l)": return "love.png";
            case "(h)": return "hot.png";
            case ":-$":
            case ":$":  return "embarassed.png";            
            default:    return "default.png";	
        }
    };
}