﻿var WallArtGUI = new __WallArtGUI;

var MaxEngravingWidth = 24;

function CostCalculator()
{
	this.PackingCost = 0.02;
    this.MatCost = 0;
	this.FrameCost = 0;
	this.FrameWidth = 0;
	this.Height = 0;
	this.Width = 0;
	this.IsWholesale = false;
	this.Factor = 2;
	
	this.OperatingCosts = new OperatingCosts;
	this.OperatingCosts.GUIType = "custom frames";
	
	this.UpdateCost = function(pProductHeight, pProductWidth)
	{	
		this.OperatingCosts.IsWholesale = this.IsWholesale;
		this.Height = parseFloat(pProductHeight);
		this.Width= parseFloat(pProductWidth); 
		
		var TotalCost = (this.GetMatCost() + this.GetFrameCost() + this.GetPackingCost());
		var OperatingAdjustment = this.OperatingCosts.GetOperatingCost(
			this.Factor, this.GetPackingCost(), this.GetMatCost(), this.GetFrameCost());
		var Price = TotalCost + (OperatingAdjustment * this.WholeSaleCost());

		document.getElementById("WallArtGUI_Cost").innerHTML = WallArtCore.Math.FormatCurrency(Price);
		if (Price > 0)
		{
			document.getElementById("tblCost").style.visibility = "visible";
		}
	}

	this.GetPackingCost = function(pFactor)
	{
		pFactor = (pFactor == null) ? parseFloat(this.Factor) : parseFloat(pFactor);
		
		if (parseFloat(this.Height) != NaN && parseFloat(this.Width) != NaN)
		{
			var MatHeight = this.Height;
			var MatWidth = this.Width;
			
			if (parseFloat(this.FrameWidth) != 0)
			{
				MatHeight = (MatHeight - (2 * parseFloat(this.FrameWidth)));
				MatWidth = (MatWidth - (2 * parseFloat(this.FrameWidth)));
			}
			return (parseFloat(this.PackingCost) * parseFloat(MatHeight) * parseFloat(MatWidth)) * this.WholeSaleCost() * pFactor;
		}
		else
		{
			return 0;
		}
	}
	
	this.GetFrameCost = function(pWidth, pHeight, pCost, pFactor)
	{
		pCost = pCost ? pCost : this.FrameCost;
		pFactor = pFactor ? parseFloat(pFactor) : parseFloat(this.Factor);
		
		if (pWidth == null)
		{
			pWidth = parseFloat(this.Width) - (2 * parseFloat(this.FrameWidth));
		}
		if (pHeight == null)
		{
			pHeight = parseFloat(this.Height) - (2 * parseFloat(this.FrameWidth));
		}
		
		if (parseFloat(pCost) != NaN && parseFloat(pHeight) != NaN && parseFloat(pWidth) != NaN)
		{
			return (parseFloat(pCost) * parseFloat(pHeight) * parseFloat(pWidth)) * this.WholeSaleCost() * pFactor;
		}
		else
		{
			return 0;
		}
	}
	
	this.GetMatCost = function(pFactor)
	{
		pFactor = (pFactor == null) ? parseFloat(this.Factor) : parseFloat(pFactor);

		if (parseFloat(this.MatCost) != NaN && parseFloat(this.Height) != NaN && parseFloat(this.Width) != NaN)
		{
			var MatHeight = this.Height;
			var MatWidth = this.Width;
			
			if (parseFloat(this.FrameWidth) != 0)
			{
				MatHeight = (MatHeight - (2 * parseFloat(this.FrameWidth)));
				MatWidth = (MatWidth - (2 * parseFloat(this.FrameWidth)));
			}
			
			return (parseFloat(this.MatCost) * parseFloat(MatHeight) * parseFloat(MatWidth)) * this.WholeSaleCost() * pFactor;
		}
		else
		{
			return 0;
		}
	}
	
	this.WholeSaleCost = function()
	{
		var Charge = ((this.IsWholesale == true) ? 1 : WallArtGUIClientMarkUp);
		
		return Charge;
	}
		
	this.UpdateFrameCosts = function()
	{
		var ControlName = WallArtCore.HtmlElements.GetElementId("spcFrameControl_pnlFrames", "DIV");
		var Control = document.getElementById(ControlName);
		
		if (Control != null)
		{
			var Divs = Control.getElementsByTagName("DIV"); 
			if (Divs != null)
			{
				for (iDiv = 0; iDiv < Divs.length; iDiv++)
				{
					var FrameCost = WallArtCore.HtmlElements.GetObjectAttribute(Divs[iDiv], "cost");
					var FrameWidth = WallArtCore.HtmlElements.GetObjectAttribute(Divs[iDiv], "framewidth");
					var FrameFactor = WallArtCore.HtmlElements.GetObjectAttribute(Divs[iDiv], "factor");
					
					if (FrameCost != "" && FrameWidth != "" && FrameFactor != "")
					{
						var NewWidth = parseFloat(this.Width) - (2 * parseFloat(this.FrameWidth));
						var NewHeight = parseFloat(this.Height) - (2 * parseFloat(this.FrameWidth));
						var thisCost = this.GetFrameCost(NewWidth, NewHeight, FrameCost, FrameFactor);
						var OperatingAdjustment = this.OperatingCosts.GetOperatingCost(
							FrameFactor, this.GetPackingCost(FrameFactor), this.GetMatCost(FrameFactor), thisCost);
						
						thisCost += this.GetMatCost(FrameFactor) + this.GetPackingCost(FrameFactor) + (OperatingAdjustment * this.WholeSaleCost());
						
						Divs[iDiv].innerHTML = WallArtCore.Math.FormatCurrency(thisCost);
					}
				}
			}
		}
	}
}

function OpeningInterface()
{
    this.Openings = "";
    
    this.UpdateCaption = function()
    {
        var Caption = (this.Openings == "") ? "None Selected" : this.FormattedOpenings();
        document.getElementById("BuildGUIAdd_Openings").innerHTML = "<i>Openings: </i><b>" + Caption + "</b>";
    }
    
    this.AddOpening = function(pOpening)
    {
        this.Openings += (this.Openings != "" ? "$" : "") + pOpening;
        this.UpdateCaption();
    }
    
    this.ClearOpenings = function()
    {
        this.Openings = "";
        this.UpdateCaption();
    }
    
    this.GetOpenings = function()
    {
        return this.Openings;
    }
    
    this.RemoveOpening = function(pOpening)
    {
        var myOpenings = this.Openings.split("$");
		var NewOpenings = "";
		
		for (var iCull = 0; iCull < myOpenings.length; iCull++)
		{
			if (iCull != pOpening)
			{			
				NewOpenings += (NewOpenings != "" ? "$" : "") + myOpenings[iCull];
			}
		}
		
		confirm("Are you sure you want to remove the selected image?");
		CustomDialog.Closed = function()
		{
			if (CustomDialog.Result == CustomDialog.Yes)
			{
				WallArtGUI.Preview.Openings.Openings = NewOpenings;
				WallArtGUI.Preview.Openings.UpdateCaption();
				setTimeout("WallArtGUI.ShowPreview()", 100);
			}
		}
    }
    
    this.FormattedOpenings = function()
    {
        var CurrentText = this.Openings;
        
        CurrentText = ReplaceText(CurrentText, "%20", " ");
        CurrentText = ReplaceText(CurrentText, "O ", "Oval ");
        CurrentText = ReplaceText(CurrentText, "R ", "Rectangle");
        CurrentText = ReplaceText(CurrentText, "$", ", ");
        
        var AllElements = CurrentText.split(", ");
        var AllShapes = new Object;
        
        for (var iElement = 0; iElement < AllElements.length; iElement++)
        {
            AllShapes[AllElements[iElement]] = (isNaN(AllShapes[AllElements[iElement]]) ? 1 : AllShapes[AllElements[iElement]] + 1); 
        }
        
        CurrentText = "";
        for (key in AllShapes) 
        { 
            if (AllShapes.hasOwnProperty(key))
            {
                CurrentText += (CurrentText != "" ? ", " : "") + "(" + AllShapes[key] + ") " + key;
            }
        }
           
        return CurrentText;
        
        function ReplaceText(pText, pWith, pWhat)
        {
            while (pText.indexOf(pWith) >= 0)
            {
                pText = pText.replace(pWith, pWhat);
            }
            
            return pText;
        }
    }
}

function TextInterface()
{
    this.Text = "";
    this.FontSize = 2;
    this.FontFamily = "";
    this.TextControlName = "";
    this.FontSizeControlName = "";
    this.FontFamilyControlName = "";
    
    this.GetText = function()
    {
        return this.Text;
    }
    
    this.GetImageParams = function()
    {
        return "&lasermattext=" + WallArtCore.Text.FormatToImage(this.Text) + "&fontsize=" + this.FontSize + "&fontfamily=" + this.FontFamily;
    }
    
    this.SetFromCart = function(pFontName, pFontSize, pText)
    {
		this.Text = WallArtCore.Text.FormatToImage(pText, true);
		this.FontSize = parseFloat(pFontSize);
		this.FontFamily = pFontName + (pFontName.toLowerCase().indexOf(".ttf") > 0 ? "" : ".ttf");
		
		var FontSizeControl = document.getElementById(this.FontSizeControlName);
		if (FontSizeControl != null)
		{
			for (iSize = 0; iSize < FontSizeControl.options.length; iSize++)
			{
				if (FontSizeControl.options[iSize].value == pFontSize)
				{
					FontSizeControl.options[iSize].selected = true;
				}
			}
		}
		
		var FontFamilyControl = document.getElementById(this.FontFamilyControlName);
		if (FontFamilyControl != null)
		{
			var Fonts = FontFamilyControl.getElementsByTagName("IMG");
			if (Fonts != null)
			{
				for (var iFont = 0; iFont < Fonts.length; iFont++)
				{
					var FontSource = WallArtCore.HtmlElements.GetObjectAttribute(Fonts[iFont], "alt");
					if (FontSource.toLowerCase() == pFontName.toLowerCase())
					{
						if (Fonts[iFont].fireEvent) 
						{ 
							Fonts[iFont].fireEvent("onclick");
						} 
						else if(document.createEvent) 
						{ 
							var EventTrigger = document.createEvent("HTMLEvents");
							EventTrigger.initEvent("click", true, true);
							Fonts[iFont].dispatchEvent(EventTrigger);
						} 
					}
				}
			}
		}
		
		var TextControl = document.getElementById(this.TextControlName);
		if (TextControl != null)
		{
			TextControl.value = this.Text;
		}
    }
}

function ImageInterface()
{
	this.RootUrl = "";
	this.PreviewControlName = "";
	this.ParsedHeight = 0;
	this.ParsedWidth = 0;
	this.ParseUrl = "";
	this.ShowGrid = false;
	this.Iteration = 1;
	
	this.Mat = new MatInterface();
	this.Frame = new FrameInterface();
	this.Cost = new CostCalculator();
	this.Openings = new OpeningInterface();
	this.Text = new TextInterface();
	this.Errors = new ErrorInterface();
	
    this.LoadPreview = function(pPreviewControlName)
	{
		this.PreviewControlName = pPreviewControlName;
		
		var ImagePreview = document.getElementById(this.PreviewControlName)
		if (ImagePreview != null)
		{
			var ImageInfo = this.GetImageInfo();
			
			if (ImageInfo.Url != "")
			{
				ImagePreview.src = ImageInfo.Url;
				this.ParsedUrl = ImageInfo.Url;
				this.ParsedHeight = ImageInfo.Height;
				this.ParsedWidth = ImageInfo.Width;
			}
		}
	}

	this.GetImageInfo = function()
	{
		var BaseUrl = this.RootUrl + this.GetImageParameters() + "&output=data";
		var ImageData = WallArtCore.DoCallBack(BaseUrl, false); 
		var ParseResult = this.ParseImageData(ImageData); 
		var ImageUrl = "";

		if (ParseResult.Code == -1)
		{
			var thisLoop = 0;
			while (ParseResult.Code == -1 && thisLoop < 100)
			{
				ImageData = WallArtCore.DoCallBack(BaseUrl, false);
				ParseResult = this.ParseImageData(ImageData);
				thisLoop += 1;
			}
		}
		
		if (ParseResult.Code == 0)
		{			
			ImageUrl = BaseUrl.replace("&output=data", "");
		}
		
		return {Url:ImageUrl, Height:ParseResult.Height, Width:ParseResult.Width};
	}
	
	this.GetImageParameters = function()
	{
		var _Params = "?c=" + this.Iteration;
		this.Iteration += 1;
		
		_Params += "&usegrid=" + this.ShowGrid;

		if (this.Mat.GetImage() != "")
		{
			_Params += "&mat=" + this.Mat.GetImage();
		}
		if (this.Frame.GetImage() != "")
		{
			_Params += "&frame=" + this.Frame.GetImage();
		}
        if (this.Openings.GetOpenings() != "")
        {
            _Params += "&fontmatopening=" + this.Openings.GetOpenings();
        }
        if (this.Text.GetText() != "")
        {
            _Params += this.Text.GetImageParams();
        }
        
		return _Params;
	}
	
	this.ParseImageData = function(pImageData)
	{
		var xmlImageData = WallArtCore.Xml.Parse(pImageData); 
		var ParentNode = xmlImageData.getElementsByTagName("image")[0];
		var ImageError = WallArtCore.Xml.GetNodeValue(ParentNode.childNodes[3]);
		var ImageResultCode = 0;
		var imgHeight = 0;
		var imgWidth = 0;
		
		if (ImageError != "")
		{
			ImageResultCode = ((ImageError.toLowerCase().indexOf("error: ") > 0) ? -1 : 1);
			this.HandleError(ImageError);
		}
		else
		{
			var ProductHeight = WallArtCore.Xml.GetNodeValue(ParentNode.childNodes[5]);
			var ProductWidth = WallArtCore.Xml.GetNodeValue(ParentNode.childNodes[6]);
			var ImageCount = WallArtCore.Xml.GetNodeValue(ParentNode.childNodes[7])
			
			ParseImageMap(WallArtCore.Xml.GetNodeValue(ParentNode.childNodes[4]));
			ParseImageDimensions(ProductHeight, ProductWidth);

			this.Cost.UpdateCost(ProductHeight, ProductWidth);
		}
		
		return {Code:ImageResultCode, Height:imgHeight, Width:imgWidth};
		
		function ParseImageDimensions(pHeight, pWidth)
		{
			document.getElementById("BuildGUIHeight").innerHTML = WallArtCore.Math.Round(pHeight, 4);
			document.getElementById("BuildGUIWidth").innerHTML = WallArtCore.Math.Round(pWidth, 4);
		}
		
		function ParseImageMap(pMapData)
		{
			pMapData = ((pMapData == undefined) ? "" : pMapData);
	
			while (pMapData.indexOf("[") >= 0)
			{
				pMapData = pMapData.replace("[","<");
			}
			while (pMapData.indexOf("]") >= 0)
			{
				pMapData = pMapData.replace("]",">");
			}
			while (pMapData.indexOf("~") >= 0)
			{
				pMapData = pMapData.replace("~","\"");
			}
			while (pMapData.indexOf(".5") >= 0)
			{
				pMapData = pMapData.replace(".5","&frac12;");
			}
			
			document.getElementById("WallArtImageMap").innerHTML = pMapData;
		}
	}
	
	this.HandleError = function(pErrorValue)
	{
		switch (pErrorValue)
		{
			case "40011":
				var Element = WallArtCore.HtmlElements.GetElementId("spcLaserMats_txtText", "TEXTAREA");
				this.Errors.ShowWarning(ErrorCode_40011, Element);
				break;
				
			case "4003":
				this.Errors.ShowWarning(ErrorCode_4003, "tbcPictureMats");
				break;
		}
	}
}

function __WallArtGUI()
{
	this.BackgroundControl = "";
	this.MatSet = false;
	
	this.TabSelector = new WallArtTabSelector();
	this.Preview = new ImageInterface();
	
	this.AddToCart = function(UpdateReminder, pEdit, pKey, pRawUrl)
	{
		var MatValid = (this.Preview.Mat.GetImage() != "");
		var FrameValid = (this.Preview.Frame.GetImage() != "");
		var CanAdd = true;
		
		if (!MatValid || !FrameValid)
        {
            var MatAndFrame = ((!MatValid) ? "mat" : "") + ((!MatValid && !FrameValid) ? " and " : "") + ((!FrameValid) ? "frame" : "");
            var Message = "Please select a " + " to continue.";
            CanAdd = false;
            alert(Message, "Invalid Mat/Frame");
        }
        
		if (CanAdd)
		{
			UpdateReminder = (UpdateReminder == null) ? true : UpdateReminder;
			pEdit = (pEdit == null) ? "add" : pEdit;
			pKey = (pKey == null) ? "" : pKey;
					
			var FontParams = this.Preview.Text.GetImageParams();
			var Params = "&csku=" + this.Preview.Mat.Code + this.Preview.Frame.Code;
			Params += "&psku=CUSTOM";
			Params += "&price=" + document.getElementById("WallArtGUI_Cost").innerHTML.replace("$","");
			Params += "&pid=0";
			Params += "&height=" + document.getElementById("BuildGUIHeight").innerHTML;
			Params += "&width=" + document.getElementById("BuildGUIWidth").innerHTML;
			Params += "&matimage=" + this.Preview.Mat.FileName;
			Params += "&frameimage=" + this.Preview.Frame.FileName;
			Params += FontParams.replace("fontfamily", "font").replace("lasermattext", "lasertext").replace(".ttf", "");
			Params += "&openings=" + this.Preview.Openings.FormattedOpenings();
			Params += "&ufopenings=" + this.Preview.Openings.Openings;
			Params += ((pKey == "") ? "" : "&key=" + pKey);	    

			WallArtCatalog.AdjustShoppingCart(pEdit, Params, false);
			if (UpdateReminder == true)
			{
				WallArtCatalog.UpdateCartReminder();
			}
			
			if (pRawUrl != null)
			{
				WallArtCore.Navigate("../../.." + pRawUrl);
			}
			else
			{
				WallArtCatalog.ConfirmAddCart(true);
			}
		}
		
		return false;
	}
	
	this.GetFromCart = function(pFrame, pMat, pLaserText, pFontName, pFontSize, pOpenings)
	{
		var ThisFrameValue = this.Preview.Frame.SetFrameFromCart(pFrame);
		var ThisMatValue =	 this.Preview.Mat.SetMatFromCart(pMat);
		
		this.Preview.Cost.FrameCost = ThisFrameValue.Cost;
		this.Preview.Cost.FrameWidth = ThisFrameValue.Width;
		this.Preview.Cost.Factor = ThisFrameValue.Factor;
		this.Preview.Cost.MatCost = ThisMatValue;
		this.Preview.Openings.Openings = pOpenings;
		this.Preview.Openings.UpdateCaption();
		this.Preview.Text.SetFromCart(pFontName, pFontSize, pLaserText);
		this.SetPrimaryToSecondary();
		
		if (ThisMatValue > 0 || ThisFrameValue.Cost > 0)
		{
			this.MatSet = true;
		}
		
		this.TabSelector.Select("tbcFrames", true);
		this.TabSelector.Open("tbcPictureMats");
		this.ShowPreview();
	}
	
	this.AddMatOpening = function(pImage)
	{
	    this.Preview.Openings.AddOpening(pImage);
	    this.ShowPreview();
	}
	
	this.ClearShapes = function()
	{
	    this.Preview.Openings.ClearOpenings();
	    this.ShowPreview();
	}
	
	this.ContinueFromPrimary = function(pImage)
	{
	    this.Preview.Openings.AddOpening(pImage);
	    this.SetPrimaryToSecondary();
		this.OpenMatsAndFrames();
		
		return false;
	}
	
	this.OpenMatsAndFrames = function()
	{
	    this.TabSelector.Select("tbcFrames");
		this.TabSelector.Select("tbcPictureMats"); 
		
		if (!this.MatSet)
		{
			this.Preview.Mat.SetMatImage("heron");
			this.Preview.Frame.SetFrameImage("black.gif");
			
			this.MatSet = true;
		}
		else
		{
		
		}
	}
	
	this.SetGrid = function(pChecked)
	{
		this.Preview.ShowGrid = pChecked;
		this.ShowPreview();
	}
	
	this.SetPrimaryToSecondary = function()
	{
		var divPrimary = document.getElementById("divPictureMats");
		
		if (divPrimary != null)
		{
			divPrimary.className = divPrimary.className.replace(" Full", " Static Small");
		}
		
		this.TabSelector.RemovePrimary("tbrPrimary", "tbrSecondary,tbrPreview");
		this.TabSelector.CanSelect = true;
	}
	
	this.UpdateEngravingTab = function()
	{
		var cellEngraving = document.getElementById("tbcLaserMats");
		var floatWidth = parseFloat(document.getElementById("BuildGUIWidth").innerHTML);
		
		if (cellEngraving != null)
		{
			if (floatWidth > parseFloat(MaxEngravingWidth))
			{
				if (cellEngraving.className.indexOf(" Hidden") < 0)
				{
					cellEngraving.className = cellEngraving.className += " Hidden";
					if (this.Preview.Text.Text != "")
					{
						this.Preview.HandleError("40011");
					}
				}
			}
			else
			{
				if (cellEngraving.className.indexOf(" Hidden") > 0)
				{
					cellEngraving.className = cellEngraving.className.replace(" Hidden", "");
				}
			}
		}
	}
	
	this.ShowPreview = function()
	{
	    this.Preview.LoadPreview(this.PreviewControlName);
		this.UpdateEngravingTab();
	}
	
	this.RemoveOpening = function(pOpening)
	{
	    this.Preview.Openings.RemoveOpening(pOpening);
	}
	
	this.ResetPreviewUI = function()
	{
	}
	
	this.UpdateFontSize = function(pFontSize)
    {
        this.Preview.Text.FontSize = pFontSize;
        this.ShowPreview();
    }
    
    this.UpdateFontFamily = function(pFontFamily)
    {
        this.Preview.Text.FontFamily = pFontFamily;
        this.ShowPreview();
    }
    
	this.UpdateFrame = function(pFileName, pCost, pCode, pWidth, pRender, pFactor)
	{
		this.Preview.Frame.SetImage(pFileName, pCost, pCode, pWidth, pRender, pFactor)
		this.Preview.Cost.FrameCost = parseFloat(pCost);
		this.Preview.Cost.FrameWidth = parseFloat(pWidth); 
		this.Preview.Cost.Factor = parseFloat(pFactor);
		this.ShowPreview();

		if (pCode != "0" && pWidth != "0")
		{
			this.Preview.Cost.UpdateFrameCosts();
		}
	}
	
	this.UpdateFrameCategory = function(pCategory)
	{
		var Url = WallArtGUIUrl;
		Url += (Url.indexOf("?") > 0 ? "&" : "?") + "type=getframes"; 
		Url += "&gui=1";
		Url += "&category=" + pCategory;
		Url += "&usenoframe=false";
		
		var FramesHTML = WallArtCore.DoCallBack(Url, false);
		var ControlName = WallArtCore.HtmlElements.GetElementId("spcFrameControl_pnlFrames", "DIV");
		var Control = document.getElementById(ControlName);
		
		if (Control != null)
		{
			Control.innerHTML = FramesHTML;
			this.Preview.Cost.UpdateFrameCosts();
		}
	}
	
	this.UpdateMat = function(pFileName, pCost, pCode)
	{
		this.Preview.Mat.SetImage(pFileName, pCode);
		this.Preview.Cost.MatCost = pCost;
		this.ShowPreview();
		this.Preview.Cost.UpdateFrameCosts();
	}
	
	this.UpdateText = function(pValue)
	{
	    this.Preview.Text.Text = pValue;
	    this.ShowPreview();
	    
	    return false;
	}
}
