﻿var xtItemId=0;
var do_d_up=1;
function InitializeDiamond(diamondPreference)
{
    diamondPreferences = null;
    
    var dp = eval('(' + diamondPreference + ')'); 
    diamondPreferences = new DiamondPreference();
    diamondPreferences.ShapeId = dp.ShapeId;
    
    diamondPreferences.MinCarat = dp.MinCarat;
    diamondPreferences.MaxCarat = dp.MaxCarat;
    
    diamondPreferences.Colors = dp.Colors;
    diamondPreferences.Clarities = dp.Clarities;
    diamondPreferences.Certs = dp.Certs;
    
    diamondPreferences.MinPrice=dp.MinPrice;
    diamondPreferences.MaxPrice = dp.MaxPrice;
    
    diamondPreferences.Cuts = dp.Cuts;
    diamondPreferences.Pols = dp.Pols;
    diamondPreferences.Symms = dp.Symms;
    diamondPreferences.Flos = dp.Flos;
    
    diamondPreferences.FancyColors = dp.FancyColors;
    diamondPreferences.FancyIntensities = dp.FancyIntensities;
    
    diamondPreferences.MinRatio = dp.MinRatio;
    diamondPreferences.MaxRatio = dp.MaxRatio;
    
    diamondPreferences.ResultsPerPage = dp.ResultsPerPage;
    
    //set this in the drop down as well
    
    diamondPreferences.CurrentPageNumber = dp.CurrentPageNumber;    
    diamondPreferences.ShowAdvanced = dp.ShowAdvanced;
    diamondPreferences.ShowPairs = dp.ShowPairs;
    diamondPreferences.DiamondView = dp.DiamondView;
    currentDiamond = new CurrentDiamond();
}

function UpdateShapesOnDiamondFilter(shapes, itemId)
{    
    xtItemId = itemId;
    //disable all shapes first, go through the shapes passed in and enable shapes        
    //$("[id*=sha_]").removeAttr('onclick').removeClass('diamond_control_shape_select').removeClass('diamond_control_select_bg').addClass('diamond_control_shape_select_nocursor');
    $("[id*=sha_]").removeClass('diamond_control_select_bg');
    //set the unvailable image for eache td
    $("table#tblFilterDiamondShapes td img").attr('src',function(index, attr){ if (attr.indexOf('-un.png') < 0){ attr=attr.replace('.png', '-un.png'); return attr; }});

    //enable shape  that item comes in
    //go through all the shapes on the diamond filter
    //AND
    var selectedShapeStillExists = false;
    for(var i=0;i<shapes.length;i++)
    {   
        $("[id=ctl00_CenterContentPlaceHolder_DiamondsFilter_imgSha_" + shapes[i].Id + "]").attr('src','/images/shape-' + shapes[i].Name + '.png');
        var td  = document.getElementById('sha_' + shapes[i].Id);
        td.ShapeId = shapes[i].Id;
        $("[id=sha_" + shapes[i].Id + "]").removeClass('diamond_control_shape_select_nocursor').addClass('diamond_control_shape_select').addClass('diamond_control_select_bg');;
        if(diamondPreferences.ShapeId==shapes[i].Id)
        {
            selectedShapeStillExists = true;
        }
    }
    
    if(selectedShapeStillExists)
        do_d_up = 0;
    
    if(!selectedShapeStillExists) //select the first available shape because we dont have anything else!
    {
        diamondPreferences.ShapeId = shapes[0].Id;
        //update diamond preference in the session
        UpdateDiamondPreference(diamondPreferences);
        var firstTd = document.getElementById('sha_' + diamondPreferences.ShapeId);
        //remove that class for all the tds
        $("[id*=sha_]").removeClass('diamond_control_select_bg_selected');
        $("[id=sha_" + diamondPreferences.ShapeId + "]").addClass('diamond_control_select_bg_selected');        
        SelectShape(diamondPreferences.ShapeId, firstTd);
    }
    
}

function InitDiamondControls()
{
    if(diamondPreferences.ShowAdvanced)
    {        
        $("#diamond_control_advanced_container").removeClass("HiddenDiv");
         $("#diamond_control_advanced_container").animate({"height": "toggle"}, { duration: 1000 });
    }
    else
    {
        $("#diamond_control_advanced_container").addClass("HiddenDiv");
        
    }
    
    SetResultsPerPageInDropDown();
    
    //if is round i don't shop ratioSlider
    if (diamondPreferences.ShapeId == 1)
        document.getElementById('ratioContainer').style.display = 'none';
    else
        document.getElementById('ratioContainer').style.display = 'block';
}


//Called when the user clicks on a shape
function SelectShape(shapeId, el)
{   
    //if is round i don't shop ratioSlider
    if (shapeId == 1)
        document.getElementById('ratioContainer').style.display = 'none';
    else
    {
        document.getElementById('ratioContainer').style.display = 'block';
        //do the min max
        if (el!=null && el.getAttribute('MinRatio') !=null )
        {
            diamondPreferences.MinRatio = el.getAttribute('MinRatio');
            diamondPreferences.MaxRatio = el.getAttribute('MaxRatio');
        }
        
        //
        diamondPreferences.MinRatio = '1.00';
        diamondPreferences.MaxRatio = '5.00';
        document.getElementById('ratioMin').innerHTML=diamondPreferences.MinRatio;
        document.getElementById('ratioMax').innerHTML=diamondPreferences.MaxRatio;
        
        OnRatioSliderLoad($find('ctl00_CenterContentPlaceHolder_DiamondsFilter_SliderRatio'),null);
        RedrawSliderRatio();
    }
    
    //1. Update the current shape in the session
    if(diamondPreferences.ShapeId != shapeId)
    {   
        //stop the video
        Stop();
        StopMove();
        
        $("[id*=sha_]").removeClass('diamond_control_select_bg_selected');      
        $("[id=sha_" + diamondPreferences.ShapeId + "]").addClass('diamond_control_select_bg');        
        $("[id=sha_" + shapeId + "]").addClass('diamond_control_select_bg_selected').removeClass('diamond_control_select_bg');
        
        diamondPreferences.ShapeId = shapeId;       
        
        if (diamondPreferences.DiamondView !=3)
        {
            //remove the ratios from other shapes
            diamondPreferences.MinRatio = 1.00; //reset ratios here - diamond preferences should have it already
            diamondPreferences.MaxRatio = 5.00;//reset ratios here
        }
        document.getElementById('ratioMin').innerHTML=diamondPreferences.MinRatio;
        document.getElementById('ratioMax').innerHTML=diamondPreferences.MaxRatio;
        
        //update diamond preference in the session
        UpdateDiamondPreference(diamondPreferences);
        UpdateSubMenuItems(); //find in productscript.js   
        UpdateResults(true);
    }
    
}

function FilterClicked(attGroup, el)
{
    
    var props = GetElementProperties(el);
    if(props.IsSelected==0)
        props.IsSelected = true;
    else if(props.IsSelected==1)
        props.IsSelected = false;
    
    UpdateClass(props); //GUI change immediate is better than waiting for requests!
    UpdateFilter(attGroup, props.AttributeId, props.IsSelected);
    diamondPreferences.CurrentPageNumber = 0; //reset to the first page
    
    UpdateResults(false);
}

function InitializeDiamondResults()
{
    if(do_d_up==1 || document.getElementById('diamond_results_container').innerHTML.indexOf('diamond') == -1)
        UpdateResults(false);
}
function ShowLoading(elementName)
{
    document.getElementById(elementName).style.display='block';
}
function HideLoading(elementName)
{
    document.getElementById(elementName).style.display='none';
}

//update the diamond preference in the session
function UpdateDiamondPreference(diamondPreferences)
{
    Website.WebServices.WebService.UpdateDiamondPreference(diamondPreferences, GetCookie(), 
         function(success)
         {                        
            //reset the values for the slider
		    OnCaratSliderLoad($find('ctl00_CenterContentPlaceHolder_DiamondsFilter_SliderCarat'),null);                      
         },
         function(error)
         {          
         });
}



function UpdateResults(doUpdate)
{
    document.getElementById('no_results_found').style.display = 'none';
    //filter has been updated, update results and the session o!
    document.getElementById('lblDiamondsCount').innerHTML = '';
    document.getElementById('lblNoDiamondForSimplified').innerHTML = '&nbsp;';
    ShowLoading('when_loading_diamonds');
    if (diamondPreferences.DiamondView==1)
        ShowLoading('divLoadingForSimplified');
    
    if (xtItemId == -3)
    {
        document.getElementById('td_col_Cut').style.display = 'none';
        document.getElementById('td_col_Intensity').style.display = 'table-cell';
    }else
    {
        document.getElementById('td_col_Cut').style.display = 'table-cell';
        document.getElementById('td_col_Intensity').style.display = 'none';
    }
    
    Website.WebServices.WebService.GetDiamonds(diamondPreferences, xtItemId, GetCookie(), 
        function(result)
        {
            HideLoading('when_loading_diamonds');
            if (diamondPreferences.DiamondView==1)
                HideLoading('divLoadingForSimplified');
            var diamonds = eval('(' + result+ ')'); 
            
            document.getElementById('diamond_results_container').innerHTML = '';
            
            if(diamondPreferences.ShapeId>1)//not round
                document.getElementById('td_col_Lw').style.display = 'table-cell';
            else
                document.getElementById('td_col_Lw').style.display = 'none';                
                
            if(diamonds.ObjectCollection.length>0)
            {
                for(var i=0;i<diamonds.ObjectCollection.length;i++)
                {
                    DrawDiamond(diamonds.ObjectCollection[i], i);
                }
                SelectDiamond(diamonds.ObjectCollection[0]);           
            }
            else
            {
                if(diamondPreferences.DiamondView==1)
                {
                    document.getElementById('lblNoDiamondForSimplified').innerHTML='No diamonds found matching your criteria, please change your preferences.';
                }else
                {
                    document.getElementById('lblDiamondsCount').innerHTML='No diamonds found matching your criteria';
                    document.getElementById('no_results_found').style.display = 'block';
                    InitializePaging(0, diamondPreferences.ResultsPerPage);
                }
            }
            
            if(diamonds.SingleObject!=null && diamonds.SingleObject!=undefined)
            {
                document.getElementById('lblDiamondsCount').innerHTML = diamonds.SingleObject.TotalNumberString;
                InitializePaging(diamonds.SingleObject.TotalNumber, diamondPreferences.ResultsPerPage);
            }
            $("#diamond_control_results").animate({ scrollTop: 0 }, "quick");
        },
        function(error)
        {
        });
}

function UpdateFilter(attGroup, id, isSelected)
{    
    switch(attGroup)
    {
        case 'col':
            if(isSelected==0)
                diamondPreferences.Colors = RemoveAttribute(diamondPreferences.Colors, id);
            else
                diamondPreferences.Colors = AddAttribute(diamondPreferences.Colors, id);
        break;
        case 'cla':
            if(isSelected==0)
                diamondPreferences.Clarities = RemoveAttribute(diamondPreferences.Clarities, id);
            else
                diamondPreferences.Clarities = AddAttribute(diamondPreferences.Clarities, id);
        break;
        case 'cer':
            if(isSelected==0)
                diamondPreferences.Certs = RemoveAttribute(diamondPreferences.Certs, id);
            else
                diamondPreferences.Certs = AddAttribute(diamondPreferences.Certs, id);
        break;
        case 'cut':
            if(isSelected==0)
                diamondPreferences.Cuts = RemoveAttribute(diamondPreferences.Cuts, id);
            else
                diamondPreferences.Cuts = AddAttribute(diamondPreferences.Cuts, id);
        break;
        case 'pol':
            if(isSelected==0)
                diamondPreferences.Pols = RemoveAttribute(diamondPreferences.Pols, id);
            else
                diamondPreferences.Pols = AddAttribute(diamondPreferences.Pols, id);
        break;
        case 'sym':
            if(isSelected==0)
                diamondPreferences.Symms = RemoveAttribute(diamondPreferences.Symms, id);
            else
                diamondPreferences.Symms = AddAttribute(diamondPreferences.Symms, id);
        break;
        case 'flo':
            if(isSelected==0)
                diamondPreferences.Flos = RemoveAttribute(diamondPreferences.Flos, id);
            else
                diamondPreferences.Flos = AddAttribute(diamondPreferences.Flos, id);
        break;
        case 'fancyCol':
            if(isSelected==0)
                diamondPreferences.FancyColors = RemoveAttribute(diamondPreferences.FancyColors, id);
            else
                diamondPreferences.FancyColors = AddAttribute(diamondPreferences.FancyColors, id);
        break;
        case 'fancyInt':
            if(isSelected==0)
                diamondPreferences.FancyIntensities = RemoveAttribute(diamondPreferences.FancyIntensities, id);
            else
                diamondPreferences.FancyIntensities = AddAttribute(diamondPreferences.FancyIntensities, id);
        break;
    }    
       
    //luigi
    //update diamond preference in the session
    UpdateDiamondPreference(diamondPreferences);
}
	
function SetAdvancedOptionsPreference()
{
    Website.WebServices.WebService.UpdateShowAdvancedOptionsInSession(diamondPreferences.ShowAdvanced, GetCookie(), 
        function(result)
        {
        },
        function(error)
        {
        });
}


function ShowDiamondDetails(webDiamondLight, colorId)
{ 
    document.getElementById('fly_out_info').style.display = 'block';
    
    var inner =  webDiamondLight.CodeLabel + ' ' + webDiamondLight.Code + '<br />';
    inner+=webDiamondLight.DepthLabel + ' ' + webDiamondLight.Depth + '%<br />';
    inner += webDiamondLight.TableLabel + ' ' + webDiamondLight.Table + '%<br />';
    if(colorId==0)
        inner += webDiamondLight.CutLabel + ' ' + webDiamondLight.Cut + '<br />';
    inner += webDiamondLight.PolLabel + ' ' + webDiamondLight.Pol+ '<br />';
    inner += webDiamondLight.SymmLabel + ' ' + webDiamondLight.Symm+ '<br />';
    inner += webDiamondLight.FloLabel + ' ' + webDiamondLight.Flo+ '<br />';
    inner += webDiamondLight.MeasLabel + ' ' + webDiamondLight.Meas+ '<br />';
    document.getElementById('fly_out_info_content').innerHTML  = inner;
    document.getElementById('lblShippingInfo').innerHTML = webDiamondLight.ShippingTimeLabelForDiamond;
    if (xtItemId > 0)
        document.getElementById('lblShippingInfo').innerHTML += webDiamondLight.ShippingTimeLabelForSet.replace('##TIME##', itemShippingTime);    
}

function HideDiamondDetails()
{ 
    document.getElementById('fly_out_info').style.display = 'none';
}



function DrawDiamond(diamond, i)
{
    //go through em all and add them here!
    var tbl  = document.createElement('table');
    tbl.setAttribute('cellpadding', '0');
    tbl.setAttribute('cellspacing', '0');
    var browserName = navigator.appName;
                
    var tr = tbl.insertRow(tbl.children.length);    
    tr.Light = diamond.Light; //attach for mouse over
    tr.ColorId = diamond.ColorId;
    tr.onmouseover = function()
    {
        ShowDiamondDetails(this.Light, this.ColorId); //yay!                
    }
        
    //if is IE
    if(browserName == 'Microsoft Internet Explorer')
    {   //fix flickering with IE 
        //use event 'onmouseleave' and i attach the event to the parent div
        document.getElementById('diamond_results_container').onmouseleave = function()
        {
            HideDiamondDetails();
        } 
    }else
    {   
        tr.onmouseout = function()
        {
            HideDiamondDetails();            
        }
    }
    
    //if is Chrome
    if (browserName == 'Netscape')
    {
        //for chrome set the class to the table
        tbl.setAttribute('id','diamondRow_' + diamond.Light.Code);
        tbl.Diamond = diamond;
        
        if(i%2==0)
            tbl.className = 'diamond_control_results_A';
        else
            tbl.className = 'diamond_control_results_B';
            
        tbl.onclick = function()
        {        
            SelectDiamond(this.Diamond, tbl);        
        }
    }else
    {        
        tr.setAttribute('id','diamondRow_' + diamond.Light.Code);
        tr.Diamond = diamond;
        
        if(i%2==0)
            tr.className = 'diamond_control_results_A';
        else
            tr.className = 'diamond_control_results_B';
            
        tr.onclick = function()
        {        
            SelectDiamond(this.Diamond, tr);        
        }
    }    
    
    //draw columns
    for (var j = 0; j < 9; j++) 
    {
        var td = tr.insertCell(j);
        var attach = false;
        switch(j)
        {
            case 0:
                td.setAttribute('class', 'diamond_control_results_none');
            break;
            case 1:
                var img = document.createElement('img');
                img.setAttribute('src', '../images/shape-' + diamond.ShapeImageName.toLowerCase() + '.png');
                img.setAttribute('width','14px');
                img.setAttribute('height','14px');
                img.setAttribute('alt', diamond.ShapeName);
                img.setAttribute('title', diamond.ShapeName);
                td.setAttribute('class', 'diamond_control_results_STA');
                td.appendChild(img);
            break;
            case 2:
                td.innerHTML = diamond.Carat;
                td.setAttribute('class', 'diamond_control_results_STA');
            break;
            case 3:
                td.innerHTML = diamond.Color;
                td.setAttribute('class', 'diamond_control_results_STA');
            break;
             case 4:
                td.innerHTML = diamond.Clarity;
                td.setAttribute('class', 'diamond_control_results_STA');
            break;         
            case 5:
                if (xtItemId!=-3) 
                    td.innerHTML = diamond.Cut;
                else
                    td.innerHTML = diamond.IntensityName;
                td.setAttribute('class', 'diamond_control_results_STA');
                
            break;
            case 6:                
                td.innerHTML = '<a href="#" onclick="javascript:doPopup(\'/certification_' + diamond.Code + '.html\');" >' + diamond.Cert + '</a>';
                td.setAttribute('class', 'diamond_control_results_STA_Cert');
            break;
            case 7:
                if(diamondPreferences.ShapeId>1)
                    td.innerHTML = diamondPreferences.ShapeId>1 ? diamond.Lw : '';                
                td.setAttribute('class', 'diamond_control_results_STA');
            break;
            case 8:
                td.innerHTML = diamond.Price;
                if (diamondPreferences.ShapeId==1)
                    td.setAttribute('class', 'diamond_control_results_price_no_ratio');
                else
                    td.setAttribute('class', 'diamond_control_results_price');
            break;
        }
    }
    if(diamondPreferences.ShapeId==1)
    {
        tr.deleteCell(7); //remove the lw if its round :D
    }
   document.getElementById('diamond_results_container').appendChild(tbl);
   
    
}

//Selects a diamond when the user performs a click, or the first one after the results are fetched
function SelectDiamond(diamond, tr)
{
    DisableAddToShoppingBag();
    //remove the selction and come back to the default class    
    $("[id*=diamondRow_]").removeClass('diamond_control_results_Selected').addClass(function(index){ if (index%2==0){ return 'diamond_control_results_A'; }else{return 'diamond_control_results_B';}});
    if(tr!=null)
    {        
        currentDiamond = new CurrentDiamond(); //reset the object
        currentDiamond.Diamond = diamond;
        currentDiamond.ClassName = tr.className;
        currentDiamond.Row = tr;
        tr.className='diamond_control_results_Selected';
    }
    else //default diamond, select it!
    {
        currentDiamond.Row = document.getElementById('diamondRow_' + diamond.Light.Code);
        currentDiamond.ClassName =document.getElementById('diamondRow_' + diamond.Light.Code).className;
        currentDiamond.Diamond = diamond;
        document.getElementById('diamondRow_' + diamond.Light.Code).className = 'diamond_control_results_Selected';
    }
    
    //select this diamond on the server and updat the price / image etc.
    //update diamond on the server
    var dc = diamond.Light.Code;
    
    if(diamondPreferences.ShowPairs)
    {        
        var codes=diamond.PairedCode.split(",");
        var firstCode='';
        var secondCode='';
        if (codes.length > 1)
        {
            firstCode = codes[0];
            secondCode = codes[1];
        }
        dc = diamond.PairedCode;             
        document.getElementById('diamondRow_' + secondCode).className = 'diamond_control_results_Selected'; 
    }
     Website.WebServices.WebService.SelectDiamond(xtItemId, dc, GetCookie(), 
     function(result)
     {
        //call a method that does the updating for picture / item price etc - so either eng rings (and others) or wbands
        UpdateImages(itemPreferences.MetalId);
        UpdateOrderInfo();
        //item desc
        UpdateItemDescription();   
     },
     function(error)
     {
     });    
       
}


//When the drop down is changed, we'll have to get more stones, etc etc
function NumberOfDiamondsChanged(ddl)
{
    diamondPreferences.ResultsPerPage = ddl.options[ddl.selectedIndex].value;
    diamondPreferences.CurrentPageNumber = 0;
    UpdateResults(false);

}

//sets the correct value in the drop down for the number of diamonds per page
function SetResultsPerPageInDropDown()
{
    var ddl = document.getElementById('NumberOfDiamondsPerPage');
    for(var i=0;i<ddl.options.length;i++)
    {
        if(ddl.options[i].value==diamondPreferences.ResultsPerPage)
        {
            ddl.selectedIndex = i;
            break;
        }
    }
}

function InitializePaging(resultsCount, resultspp)
{
    var container = document.getElementById('paging');
    container.innerHTML = '';
    if(resultsCount>0)
    {
        var ul = document.createElement('ul');
        ul.className = 'diamond_control_page_selector';
        container.appendChild(ul);
        
        var pagesPerView = 5;
        var totalPages = Math.floor(resultsCount/resultspp) + 2; //everything is 0 based
        var currentPage = diamondPreferences.CurrentPageNumber;    
        var previousPage = Number(currentPage) - 1;
	    var nextPage = Number(currentPage) + 1 ;
    	
	    var startIndex = Number(currentPage -(currentPage% 5) + 1);
	    var endIndex = startIndex + pagesPerView;
    	
	    if(endIndex>totalPages)
	    {
	        endIndex = totalPages;
	        //we may need to change the start index, if there aren't 5 page numbers to show here
            if((endIndex-startIndex)-4 <=0) //we arent showing 5 elements
            {
                //we need more previous pages
                var diff = 5- (endIndex-startIndex);
                if(startIndex-diff>0) // cant go into negative numbers!
                    startIndex-=diff;
            }
	    }
    	    
    	
	    //previous page
	    //next page
        var liPreviousPage = document.createElement('li');
        ul.appendChild(liPreviousPage);
        liPreviousPage.innerHTML = '&lt;';
        liPreviousPage.MyPageNumber = previousPage;
        liPreviousPage.onclick = function()
        {
            ChangePage(this.MyPageNumber);
        }
        if (currentPage==0)
        {
            liPreviousPage.style.display = 'none';
            $(liPreviousPage).removeClass("pagingStyle");
        }
        else
        {
            $(liPreviousPage).addClass("pagingStyle");
        }
            
        //numbers
        for(var i=startIndex;i<endIndex;i++)
        {
            var li = document.createElement('li');
            ul.appendChild(li);
            li.innerHTML = i;
            if(i==currentPage+1)
                li.className ='diamond_control_page_selected';
            else
                li.className ='';
            li.MyPageNumber = i-1;
            li.onclick = function()
            {
                ChangePage(this.MyPageNumber);
            }
        }
        
        //next page
        var liNextPage = document.createElement('li');
        ul.appendChild(liNextPage);
        liNextPage.innerHTML = '&gt;';
        liNextPage.MyPageNumber = nextPage;
        liNextPage.onclick = function()
        {
            ChangePage(this.MyPageNumber);
        }
        if (currentPage+2==totalPages)
        {
	        liNextPage.style.display = 'none';
	        $(liNextPage).removeClass("pagingStyle");
	    }
        else
        {
             $(liNextPage).addClass("pagingStyle");
        }
    }
    
}

function ChangePage(pageNumber)
{
    diamondPreferences.CurrentPageNumber = pageNumber;
    
    UpdateResults(false);
}

function SelectCaratSimplified(el,minCarat,maxCarat)
{
    var elId=el.getAttribute('Id');    
    $("[id*=simpCarat_]").removeClass('diamond_control_select_bg_selected');
    $("[id*=simpCarat_]").addClass('diamond_control_select_bg');
    $("[id=" + elId + "]").removeClass('diamond_control_select_bg');
    $("[id=" + elId + "]").addClass('diamond_control_select_bg_selected');
    UpdateDiamPrefByCarat(minCarat,maxCarat );
    
}
function UpdateDiamPrefByCarat(minCarat,maxCarat)
{
    diamondPreferences.MinCarat = minCarat;
    diamondPreferences.MaxCarat = maxCarat;
    UpdateDiamondPreference(diamondPreferences);        
    UpdateResults(false);
}    

