﻿
//Called by the code behind to intialize the controls on the page
function InitializeItem(itemPreference)
{
    var ip = eval('(' + itemPreference + ')'); 
    itemPreferences = new ItemPreferences();
    itemPreferences.MetalId = ip.MetalId;
    itemPreferences.ItemId = ip.ItemId;
    itemPreferences.RecentItems = ip.RecentItems;
}

//Called by code behind to set the default item
function SelectDefaultItem()
{
     //check if the item in the session actually exists on the page
    var itemsContainer = document.getElementById('ctl00_Header_ucTopNav_ulSubMenu');
    var found = false;
    for(var i=0;i<itemsContainer.getElementsByTagName('li').length;i++)
    {
           if(itemsContainer.getElementsByTagName('li')[i].getAttribute("itemId")==itemPreferences.ItemId)
           {
                found = true;
                break;
            }
    }
    
    if(!found)
    {
        if (itemsContainer.getElementsByTagName('li').length > 0)
        {
            $("#PanelIcons").removeClass("panelIconsDiamonds");
            $("#PanelIcons").addClass("panelIcons");            
            SelectItem(itemsContainer.getElementsByTagName('li')[0].getAttribute("itemId"));
        }
        else if (getUrlRewrite().indexOf('loose_diamonds.html') != -1 || getUrlRewrite().indexOf('round-cut-diamond.html') != -1 || getUrlRewrite().indexOf('-cut-diamond.html') != -1 || getQuerystring('SubCatId') == '14' || getUrlRewrite().indexOf('lose_diamanten.html') != -1)//if i'm in loose diamond (itemId is -1)
        {
            $("#PanelIcons").removeClass("panelIcons");
            $("#PanelIcons").addClass("panelIconsDiamonds");
            SelectItem(-1);
        }else if (getUrlRewrite().indexOf('loose_diamonds_pairs.html') != -1 || getQuerystring('SubCatId') == '15' || getUrlRewrite().indexOf('lose_diamanten_paare.html') != -1)//matching pairs (itemId is -2)
        {
            $("#PanelIcons").removeClass("panelIcons");
            $("#PanelIcons").addClass("panelIconsDiamonds");
            SelectItem(-2);
        }else if (getUrlRewrite().indexOf('coloured_diamonds.html') != -1 || getQuerystring('SubCatId') == '28' || getUrlRewrite().indexOf('farbige_diamanten.html') != -1)
        {
            $("#PanelIcons").removeClass("panelIcons");
            $("#PanelIcons").addClass("panelIconsDiamonds");
            SelectItem(-3);
        }
    }
    else
        SelectItem(itemPreferences.ItemId);
}

//Called on click or by default, to fetch the item for the current item id
function SelectItem(itemId)
{
    xtItemId = itemId;    
    itemPreferences.ItemId = itemId; //update the global variable    
    //now show it
    Website.WebServices.WebService.GetItemById(itemId, GetCookie(),false, 
     function(success)
     {
        var item = eval('(' + success + ')');
        itemShippingTime = item.SingleObject.ShippingDays;
        //quickly set the diamond preferences if this guy needs pairs
        if(item.SingleObject.HasPairs)
            diamondPreferences.ShowPairs = true;
        else
            diamondPreferences.ShowPairs = false;
        currentlySelectedItem = item;
        WriteNameAndSelectInList(item.SingleObject.Name, item.SingleObject.Id);
        ConfigureSelectedItem(item);
     },
     function(error)
     {  
     });
     
}

//After the item has been fetched from the ws, update the page
function ConfigureSelectedItem(item)
{
    //when is loose diamond id is -1 and pairs is -2
    if (item.SingleObject.Id > 0)
    {
        //2. show all its metals (and select a metal)
        DrawMetals(item.SingleObject);
        SelectMetal(itemPreferences.MetalId, item.SingleObject.Id);

        //3. show / hide diamond control / wedding band control
        SetRightSidePanel(item.SingleObject);

        //4. show variations
        if(!item.SingleObject.HasComponents)
        {
            if(item.SingleObject.HasVariations)
            {
                var comps = item.ObjectCollection[0];
                document.getElementById('containerValues').innerHTML = comps;
                document.getElementById('containerValues').style.display = 'block';
                
            }
            else if(!item.SingleObject.HasVariations)
            {
                //remove everything - another product may have had a variation before this so remove it!
                while (document.getElementById('containerValues').childNodes[0])
                {
                    document.getElementById('containerValues').removeChild(document.getElementById('containerValues').childNodes[0]);
                }
                document.getElementById('customizeContainer').style.display='none';
            }
        }
        else if(item.SingleObject.HasComponents)
        {
            var comps = item.ObjectCollection[0];
            if(comps!=undefined && comps!=null )
            {
                document.getElementById('containerValues').innerHTML = comps;
                document.getElementById('containerValues').style.display = 'block';
                document.getElementById('customizeContainer').style.display = 'block';
            }
            else
            {
                document.getElementById('containerValues').style.display = 'none';
                document.getElementById('customizeContainer').style.display = 'none';
            }
            
        }
        //5. recent items updation
        DrawRecentItems();   
    }
    else //loose diamond and matching pairs
    {
        SetRightSidePanel(item.SingleObject);
    }
    
    //stop the image video
    Stop();
    StopMove();
    tabSwitch_2(1, 2, 'tab_', 'content_');    //show always the tab that contains image gallery and call getVideos
}


//init by the webservice for when we draw components- comp is the td that was clicked
function SelectComponentAndManageVarations(comp)
{
    DisableAddToShoppingBag();
    SelectTd(comp, 'diamond_comps_tr' + comp.getAttribute("SetId"));
    comp.IsSelected=true;
    if(comp.getAttribute("Variations")!=null)
    {
        //1. select this component in the ws
        //2. draw and select one of its variations
        DrawVariations(comp.getAttribute("Variations"), comp.getAttribute("SetId"), comp.getAttribute("CompId"));
    }
    //whether or not there were are variations, we need to select this component - if there are variations
    //and the variation isnt clicked, but this is, we need to know the component id (which we do)
    //and the variation id (which the variations that drew have selected) ;)
    var currentVariationId = 0;
    if(CompVar[comp.getAttribute("CompId")]!=null || CompVar[comp.getAttribute("CompId")]!=undefined)
        currentVariationId = CompVar[comp.getAttribute("CompId")];
    //now lets call the method to get us some money  / pictures / description :D
    Website.WebServices.WebService.UpdateCompsVarsForThisItem(comp.getAttribute("CompId"),
        currentVariationId, comp.getAttribute("SetId"), GetCookie(), 
        function(retult)
        {
            UpdateImages(itemPreferences.MetalId);
            UpdateOrderInfo();
            UpdateItemDescription();  
        },
        function(error)
        {
        });
}

function DrawVariations(variations, componentSetId, compId)
{
    //clean up where first
    var vars = eval('(' + variations + ')');    
    var labelName = document.getElementById(componentSetId + '_varsLabelTable');
    labelName.innerHTML = vars.LabelName; //name of the variation group :)
    
    //in this, draw all variations for this component
    var target = document.getElementById(componentSetId + '_varsTable');
    //remove all cells and then for each variation, draw it!
    var tds = target.getElementsByTagName('td');
    for(var i=0;i<tds.length;i++) //we can assume that each component has the same variations for the time being in a composite product
    {
        tds[i].setAttribute('VariationId', vars.Variations[i].Id);
        tds[i].setAttribute('ComponentId', vars.Variations[i].ComponentId);
        tds[i].setAttribute('ComponentSetId', vars.Variations[i].ComponentSetId);
        tds[i].innerHTML =  vars.Variations[i].Name;
        if(tds[i].className.indexOf('selected')!=-1)
        CompVar[compId] = vars.Variations[i].Id;
    }
}

//method is attached on the td itself, therefore we never have to do this again
function SelectVariation(selectedVariation)
{
    DisableAddToShoppingBag();
    SelectTd(selectedVariation, 'vars_tr_' + selectedVariation.getAttribute("ComponentSetId"));
    selectedVariation.IsSelected=true;
    //from this variation we know the following
    //1. component / item id
    //2. name of the variation / variationId
    //3. component set etc etc
    //we need to update on the server, what component / variation has been selected
    //this can be multiple on the server as there can be more than one set of components each with their own variations
    //we are only going to call this if this isnt already the selected variation
//    if(CompVar!=null && CompVar[selectedVariation.getAttribute("ComponentId")]!=selectedVariation.getAttribute("VariationId"))
//    {
        Website.WebServices.WebService.UpdateCompsVarsForThisItem(selectedVariation.getAttribute("ComponentId"),
        selectedVariation.getAttribute("VariationId"), selectedVariation.getAttribute("ComponentSetId"), GetCookie(), 
        function(retult)
        {
            UpdateImages(itemPreferences.MetalId);
            UpdateOrderInfo();
            UpdateItemDescription();  
        },
        function(error)
        {
        });
//    }
}

//Updates the product name and selects it in the list of items in the top nav
function WriteNameAndSelectInList(name, id)
{
    document.getElementById('ProdName').innerHTML = name;
    
    var itemsContainer = document.getElementById('ctl00_Header_ucTopNav_ulSubMenu');
    //set all the subMenuImages to opacity=40
    $("[id*=ctl00_Header_ucTopNav_subMenuImg_]").css('opacity','0.4').css('filter','alpha(opacity = 40)');
    //set the selected subMenuimage to opacity=100
    $("[id=ctl00_Header_ucTopNav_subMenuImg_" + id + "]").css('opacity','1.0').css('filter','alpha(opacity = 100)');
    for(var i=0;i<itemsContainer.getElementsByTagName('li').length;i++)
    {
        if(itemsContainer.getElementsByTagName('li')[i].getAttribute("itemId")==id)
            itemsContainer.getElementsByTagName('li')[i].className = 'sub_menu_item_image_selected';
        else
        {
            itemsContainer.getElementsByTagName('li')[i].className = 'sub_menu_item_image';
        }
    }
 
}

//Only draws the metals this product comes in
function DrawMetals(item)
{    
    var ul = document.getElementById('metals_container_ul');
    ul.innerHTML = '';
    ul.setAttribute('width','100%');
    document.getElementById('MetalName').innerHTML = ''; //clean metal name
    
    for(i=0; i <item.ComesInMetals.length;i++)
    {
        var li = document.createElement('li');
        li.setAttribute('metalId',item.ComesInMetals[i].Id);
        li.setAttribute('metalName',item.ComesInMetals[i].Name);       
        li.MetalId = item.ComesInMetals[i].Id;
        li.ItemId = item.Id;
        li.onclick = function()
        {
            SelectMetal(this.MetalId, this.ItemId);
        }
        
        li.myName = item.ComesInMetals[i].Name;
        li.originalName = '';
        li.onmouseover = function()
        {
            this.originalName = document.getElementById('MetalName').innerHTML;
            document.getElementById('MetalName').innerHTML = this.myName;
        }
        li.onmouseout = function()
        {
            if(itemPreferences.MetalId!=this.getAttribute('metalId'))
                document.getElementById('MetalName').innerHTML = this.originalName;
        }
       
        var metImage = document.createElement('img');        
        metImage.setAttribute('alt',item.ComesInMetals[i].Name);
        metImage.setAttribute('title',item.ComesInMetals[i].Name);
       
        li.appendChild(metImage);

        switch(item.ComesInMetals[i].Id)
        {
            case 1:
                metImage.src = '../images/yellow-gold.png';
                break;
            case 2:
                metImage.src = '../images/white-gold.png';
                break;
            case 3:
                metImage.src = '../images/rose-gold.png';
                break;
            case 4:
                metImage.src = '../images/platinum.png';
                break;
            case 9:
                metImage.src = '../images/black-gold.png';
                break;
            case 10:
                metImage.src = '../images/palladium.png';
                break;  
        }
       
        ul.appendChild(li);                
    }   
    //tooltip function
    //vtip();
}

//Onclicking the metal
function SelectMetal(metalId, itemId)
{
    DisableAddToShoppingBag();
    var metalsContainer = document.getElementById('metals_container_ul');
    var selected = false;
    for(var i=0;i<metalsContainer.getElementsByTagName('li').length;i++)
    {
        if(metalId==metalsContainer.getElementsByTagName('li')[i].getAttribute('metalId'))
        {
            //found the metal we should be selecting
            metalsContainer.getElementsByTagName('li')[i].setAttribute('class','product_colour_palette_selected');
            document.getElementById('MetalName').innerHTML =  metalsContainer.getElementsByTagName('li')[i].getAttribute('metalName');
            selected = true;
        }
        else
            metalsContainer.getElementsByTagName('li')[i].setAttribute('class','product_colour_palette');
    }
    if(!selected)
    {
        //select the first metal
        metalId=metalsContainer.getElementsByTagName('li')[0].getAttribute('metalId')
        metalsContainer.getElementsByTagName('li')[0].setAttribute('class','product_colour_palette_selected');
        document.getElementById('MetalName').innerHTML = metalsContainer.getElementsByTagName('li')[0].getAttribute('metalName');
        
    }
    itemPreferences.MetalId = metalId; //update js
    
    Website.WebServices.WebService.UpdateSelectedMetalInSession(metalId, itemId, GetCookie(), 
    function(result)
    {
        //call a method that does the updating for picture / item price etc - so either eng rings (and others) or wbands
        UpdateImages(metalId);
        //get order info
        UpdateOrderInfo();
        //item desc
        UpdateItemDescription();      
    },
    function(error)
    {
        //too bad
    });
}

//Toggles display on the right whether to show the diamond bit or not
function SetRightSidePanel(item)
{   
    //hide everything first, and then show as needed
    $("#contentDiamondOptionsControl").addClass("HiddenDiv");
    document.getElementById('contentDiamondControl').style.display = 'none';
    $("#diamond_control_advanced_container").addClass("HiddenDiv");
    
    $("#contentWeddingBandControl").addClass("HiddenDiv");
    $("#customizeContainer").addClass("HiddenDiv");
    document.getElementById('customizeContainer').style.display = 'none';
    document.getElementById('diamondOptionsContainer').style.display='none';
    
    if(item.IsMashed || item.IsMasher)
    {
        document.getElementById('mashedItems').style.display = 'block';
    }
    else
    {
        document.getElementById('mashedItems').style.display = 'none';
    }
    
    //if loose diamond or matching pairs or fancy
    if (item.Id == -1 || item.Id == -2 || item.Id == -3)
    {
        document.getElementById('columnTitle2').innerHTML = item.RightSideWebsiteText;        
        
        //diamond view options
        document.getElementById('diamondOptionsContainer').style.display='block';
        document.getElementById('liDiamondOption_1').style.display='none';
        if (item.Id == -3)
        {
            //force to advanced
            diamondPreferences.DiamondView = 3;
            document.getElementById('liDiamondOption_2').style.display='none';
        }
            
        if (diamondPreferences.DiamondView==1) //don't want to show the simplified here
            ChangeDiamondView(2,false);
        else
            ChangeDiamondView(diamondPreferences.DiamondView,false);
        
        $("#contentDiamondOptionsControl").removeClass("HiddenDiv");
         document.getElementById('contentDiamondControl').style.display = 'block';
         
        //enable | disable the shapes this item comes in, on the diamond filter
        if (item.Id != -3)
            UpdateShapesOnDiamondFilter(item.ComesInShapes, item.Id);
        
        if (itemPreferences.ShowAdvanced==1) //true
            $("#diamond_control_advanced_container").removeClass("HiddenDiv");
        else
            $("#diamond_control_advanced_container").addClass("HiddenDiv");
        
        do_d_up=1;   
        InitializeDiamondResults(); //in the diamond script file - only done if the item has a centre stone :)
        document.getElementById('product_note').style.display = 'block';
        
    }//all the other items
    else
    {
        if(!item.HasComponents)
        {
            document.getElementById('columnTitle2').innerHTML = item.RightSideWebsiteText;      
            if (item.HasCentreStone)
            {
                //diamond view options
                document.getElementById('diamondOptionsContainer').style.display='block';
                document.getElementById('liDiamondOption_1').style.display='block';
                ChangeDiamondView(diamondPreferences.DiamondView,false);
                    
                $("#contentDiamondOptionsControl").removeClass("HiddenDiv");
                 
                //enable | disable the shapes this item comes in, on the diamond filter                
                UpdateShapesOnDiamondFilter(item.ComesInShapes, item.Id);
                
                if (itemPreferences.ShowAdvanced==1) //true
                    $("#diamond_control_advanced_container").removeClass("HiddenDiv");
                else
                    $("#diamond_control_advanced_container").addClass("HiddenDiv");
                
                InitializeDiamondResults(); //in the diamond script file - only done if the item has a centre stone :)
                document.getElementById('product_note').style.display = 'block';
            }//wedding band
            else if (item.IsBand)
            {
                //show band control            
                $("#contentWeddingBandControl").removeClass("HiddenDiv");
                //hide diamond control
                //inizialize wedding band control
                InizializeWeddingBand();
                //hide the product note with diamond information
                document.getElementById('product_note').style.display = 'none';
            }
            else if (item.HasVariations)
            {
                document.getElementById('customizeContainer').style.display = 'block';
            }
        }
        else //item with components
        {
            document.getElementById('customizeContainer').style.display = 'block';
            document.getElementById('columnTitle2').innerHTML = item.RightSideWebsiteText;     
            if(item.HasCentreStone)
            {         
                
                //diamond view options
                document.getElementById('diamondOptionsContainer').style.display='block';
                document.getElementById('liDiamondOption_1').style.display='block';
                ChangeDiamondView(diamondPreferences.DiamondView,false);
                                
                //show customize container
                $("#contentDiamondOptionsControl").removeClass("HiddenDiv");
                 
                UpdateShapesOnDiamondFilter(item.ComesInShapes, item.Id);
                if (itemPreferences.ShowAdvanced==1) //true
                    $("#diamond_control_advanced_container").removeClass("HiddenDiv");

                InitializeDiamondResults(); //in the diamond script file - only done if the item has a centre stone :)
                document.getElementById('product_note').style.display = 'block';
            }
            else if(!item.HasCentreStone)
            {
                $("#contentDiamondOptionsControl").addClass("HiddenDiv");
                document.getElementById('contentDiamondControl').style.display = 'none';
            }
        }
        
    }
}


function DrawRecentItems()
{
    var url = window.location.href;
    
    //url rewrite
    if (document.getElementById('ctl00_UrlRewrite').value != '' )
    {
        url = document.getElementById('ctl00_UrlRewrite').value;
    }
    
    Website.WebServices.WebService.GetRecentItemsList(url, GetCookie(),
    function(result)
    {
        document.getElementById('recentlyViewed_Container').innerHTML = ''; //erase previous
        document.getElementById('recentlyViewed_Container').innerHTML = result; //update
    },
    function(error)
    {
        
    });
}

//Updates the item id in the session and then redirects the user to the targetUrl
function SelectAndRedirect(itemId, redirectUrl)
{
    Website.WebServices.WebService.UpdateCurrentItemIdInSession(itemId, GetCookie(),
    function(result)
    {
        //result is OK - redirect
        window.location.href = redirectUrl;
    },
    function(error)
    {
    });
}

//should be in product script
function UpdateSubMenuItems()
{
 
   var ul = document.getElementById('ctl00_Header_ucTopNav_ulSubMenu');

 //get the new items
  Website.WebServices.WebService.GetSubMenuItems(diamondPreferences.ShapeId, GetCookie(), 
  function(result)
  {
    var items = eval('(' + result + ')').ObjectCollection;
    var found=false;
    
    while(ul.hasChildNodes())
    {
        ul.removeChild(ul.childNodes[0])
    };
    //write all the products now!
    for(var i=0;i<items.length;i++)
    {
        var li = document.createElement('li');
        li.ItemId = items[i].Id;
        li.setAttribute('itemId',items[i].Id);
        if(items[i].IsSelected)
        {
            li.className = 'sub_menu_item_image_selected';
            li.setAttribute('style','overflow: hidden; float: left; width: 60px; height: 74px;');
            found=true;
        }
        else
        {
            li.className = 'sub_menu_item_image';            
        }
        
        var href = document.createElement('a');
        href.ItemId = items[i].Id;
        href.onclick =function()
        {
           SelectItem(this.ItemId);
        }
        href.style.cursor = 'pointer';
        href.id = 'item_href_' + items[i].Id;
        
        var img = document.createElement('img');
        img.id = 'ctl00_Header_ucTopNav_subMenuImg_' + items[i].Id;        
        img.setAttribute('src',items[i].ImageUrl);
        img.setAttribute('itemId',items[i].Id);
        img.style.cursor = 'pointer';
        img.title = items[i].Name;
        img.setAttribute('alt',items[i].Name);
        
        //li mouseover /mouseout
        li.onmouseover = function()
        {
            removeSubMenuOpacity('ctl00_Header_ucTopNav_subMenuImg_' + this.ItemId,this );
        }
       
        li.onmouseout = function()
        {
            addSubMenuOpacity('ctl00_Header_ucTopNav_subMenuImg_' + this.ItemId,this);
        }
        
        var itemName = document.createElement('span');
        itemName.innerHTML =items[i].Name;
        href.appendChild(img);
        href.appendChild(itemName);
        li.appendChild(href);
        ul.appendChild(li);
    }
    if(items.length>11)
    {
        document.getElementById('ctl00_Header_ucTopNav_prev').style.display = 'block';
        document.getElementById('ctl00_Header_ucTopNav_next').style.display = 'block';        
        document.getElementById('ctl00_Header_ucTopNav_carousel_container').style.marginLeft = '';
    }else
    {
        document.getElementById('ctl00_Header_ucTopNav_carousel_container').style.marginLeft = '0px';
        document.getElementById('ctl00_Header_ucTopNav_prev').style.display = 'none';
        document.getElementById('ctl00_Header_ucTopNav_next').style.display = 'none';
    }
        
    //see if there is an item that is selected
    if(!found)
    {
        if (items.length > 0)
            SelectItem(items[0].Id);
    }
    
    $(".my_carousel").jCarouselLite({
                btnNext: ".next",
                btnPrev: ".prev",
                circular: false
            });      
    //show always the tab that contains image gallery and call getVideos
    tabSwitch_2(1, 2, 'tab_', 'content_');    
   
  },
  function(error)
  {    
  });
 
}


//Gets the pictures for a product from images.77diamonds.com
function UpdateImages(metalId)
{
    //do all the images now
    Website.WebServices.WebService.GetPhotos(metalId, GetCookie(), 
    function(result)
    {   
        {
            //hide all the thumbnails
            for(var i=0;i<5;i++)
            {
                document.getElementById('thumb_' + i).style.display = 'none';
                document.getElementById('thumb_' + i).Zoom = null;
                document.getElementById('thumb_' + i).BigPicture = null;
            }
            
            document.getElementById('image_zoom').removeAttribute('onclick');

            //hide big pic
            document.getElementById('bigPicture').style.display = 'none'; 
            //hide zoom pic
            document.getElementById('zoom1').setAttribute('href','#'); 
            document.getElementById('zoom1').setAttribute('path',''); 
            //put these in :D

            var photos = eval('(' + result + ')').ObjectCollection;
            var photomsg =eval('(' + result + ')').SingleObject;

            //do the size text only for centre stones!
            if(photomsg==null || photomsg==undefined || photomsg=='')
                document.getElementById('lblPictureReferenceText').innerHTML = '';
            else
                document.getElementById('lblPictureReferenceText').innerHTML = photomsg;   
                
            if (xtItemId == -3) //fancy
            {
                document.getElementById('lblPictureReferenceText').style.left = '215px';
                document.getElementById('lblPictureReferenceText').innerHTML = photomsg;               
            }else
            {
                document.getElementById('lblPictureReferenceText').style.left = '305px';
            }

            if (photos.length==0)
            {
                 //hide icon zoomIn and zoomOut
                document.getElementById('liZoomIn').style.display = 'none';
                document.getElementById('lblPictureReferenceText').innerHTML='';
                document.getElementById('liZoomOut').style.display = 'none';
                document.getElementById('image_zoom').style.cursor = '';
                document.getElementById('image_zoom').removeAttribute('onclick');
            
                //zoom container
                if (document.getElementById('wrap') != null)
                    document.getElementById('wrap').style.display = 'none';          
            }
            
            var count=0;
//            if(photos.length<=3)
//            { //remove scrolling arrows
//                document.getElementById('prevItemPicArrow').style.display = 'none';
//                document.getElementById('nextItemPicArrow').style.display = 'none';
//            }else
//            {
//                document.getElementById('prevItemPicArrow').style.display = 'block';
//                document.getElementById('nextItemPicArrow').style.display = 'block';
//            }
            for(var i=0;i<photos.length;i++)
            {
                count++;
                //zoom container
                if (document.getElementById('wrap') != null)
                    document.getElementById('wrap').style.display = 'block';  
                var liId = 'thumb_' + i;
                var imgId = 'imgThumb_' + i;
                var li = document.getElementById(liId);
                li.style.display = 'inline-block';
                                    
                li.BigPicture = photos[i].Big;
                if(photos[i].Zoom != null && photos[i].Zoom !=undefined)
                    li.Zoom = photos[i].Zoom;
                li.index = i;
                li.onmouseover = function()
                {
                    ToggleBigPicture(this);
                }
                li.onmouseout = function()
                {
                    ToggleBigPicture(currentThumbselectedLi);
                }
                li.onclick = function()
                {
                    currentPicNumber = this.index;
                    currentThumbselectedLi = this;
                }

                var thumb = document.getElementById(imgId);
                thumb.setAttribute('src',photos[i].Thumb.Path);
                thumb.setAttribute('alt',photos[i].Thumb.Alt);
                thumb.setAttribute('title',photos[i].Thumb.Title);
                        
                if(i==currentPicNumber)
                {
                    li.setAttribute('class', 'thumbnail_selected'); //update css and show big picture
                    ToggleBigPicture(li);
                    currentThumbselectedLi = li;
                }
                else if(i==photos.length-1)
                    li.setAttribute('class', 'thumbnail_last');            
            }
            
            //if didn't find the thumb i select the first one
            if(currentPicNumber>=photos.length && photos.length>0)
            {
                var firstLi= document.getElementById('thumb_0');
                firstLi.setAttribute('class', 'thumbnail_selected'); //update css and show big picture
                ToggleBigPicture(firstLi);
                currentThumbselectedLi = firstLi;    
                currentPicNumber = 0;       
            }
        }
        
    },
    function(error)
    {
    });
    
}

function ToggleBigPicture(el)
{
    $("[id*=thumb_]").removeClass("thumbnail_selected");
    $("[id="+ el.getAttribute('id') +"]").addClass("thumbnail_selected");
       
    var bigp = document.getElementById('bigPicture');   
    bigp.setAttribute('src',el.BigPicture.Path);
    bigp.style.display = 'block'; 
    
    //bigp.setAttribute('alt',el.BigPicture.Alt);
    //bigp.setAttribute('title',el.BigPicture.Title);
    if (el.Zoom != null && el.Zoom !=undefined)
    {        
        //show icon zoomIn and zoomOut
        document.getElementById('image_zoom').style.cursor = 'pointer';
        document.getElementById('image_zoom').setAttribute('onclick','CheckZoom();return false;');
        
        var zoomp = document.getElementById('zoom1');   
        zoomp.style.display = 'block'; 
        //zoomp.setAttribute('href',el.Zoom.Path);
        zoomp.setAttribute('path',el.Zoom.Path);
        if (!disableZoom)
        {  
            $('.cloud-zoom').CloudZoom();
        }
        else
        {   //if video tab open
            if (document.getElementById('content_2').style.display == 'block')
                RemoveZoom(true);
            else
                RemoveZoom(false);
        }
    }
    else
    {
        //hide icon zoomIn and zoomOut
        RemoveZoom(true);
        document.getElementById('liZoomIn').style.display = 'none';
        document.getElementById('liZoomOut').style.display = 'none';
        document.getElementById('image_zoom').style.cursor = '';
        document.getElementById('image_zoom').removeAttribute('onclick');
        
    }
}

//updates the order details - price / text etc, doesnt need to be here, doesnt rely on the product from the client
//looks up the server side info
function UpdateOrderInfo()
{   
    HideFinanceInfo();
    Website.WebServices.WebService.GetOrderInfo(GetCookie(), 
    function(result)
    {
            var orderInfo = eval('(' + result + ')');
            var order = orderInfo.SingleObject;
            
            if(order!=null && order!=undefined)
            {
                document.getElementById('orderInfo_ItemName').innerHTML = order.ItemName;
                document.getElementById('orderInfo_ItemPrice').innerHTML = order.ItemPrice;
                
                if(!order.HasDiamond)
                {
                    document.getElementById('orderInfo_DiamondName').style.display = 'none';
                    document.getElementById('orderInfo_DiamondPrice').style.display = 'none';
                }
                else
                {
                    //do the diamond bit :D
                    document.getElementById('orderInfo_DiamondName').style.display = 'block';
                    document.getElementById('orderInfo_DiamondPrice').style.display = 'block';
                    document.getElementById('orderInfo_DiamondName').innerHTML = order.DiamondName;
                    document.getElementById('orderInfo_DiamondPrice').innerHTML = order.DiamondPrice;
                }
                if(!order.HasExtras)
                {
                    document.getElementById('orderInfo_ExtrasName').style.display = 'none';
                    document.getElementById('orderInfo_ExtrasPrice').style.display = 'none';
                }
                else
                {
                    //do the EXTRA bit :D
                }
                
                document.getElementById('orderInfo_VatName').innerHTML = order.VatName;
                document.getElementById('orderInfo_VatPrice').innerHTML = order.VatPrice;
                document.getElementById('orderInfo_TotalPrice').innerHTML = order.TotalPrice;
                if(order.HasDiscount)
                {
                    document.getElementById('orderInfo_TotalPrice').innerHTML = '<s><span style=\'color:#666\'>' + order.TotalPrice + '</span></s><br />' 
                    + '<span style=\'color:#ad0000;\'>' + order.TotalDiscountPrice + '</span>';
                    document.getElementById('lblTextSale').style.display = 'inline';
                    document.getElementById('lblTextSale').innerHTML = '<br/>' + order.DiscountDescription;
                    document.getElementById('imgOffer').style.display = 'block';
                }else
		        {
			        document.getElementById('imgOffer').style.display = 'none';
			        document.getElementById('lblTextSale').style.display = 'none';
		        }
		        
                if(order.FinanceResponse!='')
                {
                    var  financeResponse = eval('(' + order.FinanceResponse + ')');
                    if(financeResponse!=null && financeResponse!=undefined)
                    {
                        document.getElementById('fincance_container').style.display='block';
                        document.getElementById('lblFinanceOffer').innerHTML = 'Purchase from £ ' + financeResponse.monthly_repayment + ' per month...';
                        //drawing finance options
                        removeAllOptions(document.aspnetForm.ddlFinanceOptions);
                        DrawFinanceOptions(order.TotalDiscountPrice);
                        DrawFinanceInfo();
                    }
                    else
                    {
                        document.getElementById('fincance_container').style.display='none';
                        HideFinanceInfo();
                    }
                }
                else
                {
                    document.getElementById('fincance_container').style.display='none';
                    HideFinanceInfo();
                }
            }
            
            
    },
    function(error)
    {
    });
}

//update the item description
function UpdateItemDescription()
{       
    Website.WebServices.WebService.GetItemDescription(GetCookie(), 
    function(result)
    {            
            var desc = eval('(' + result + ')').SingleObject;
            
            if(desc!=null && desc!=undefined)
            {                
                document.getElementById('lblProductDesc').innerHTML = desc.Description + ' ';                
                if(desc.AdditionalText!=null && desc.AdditionalText!=undefined)
                    document.getElementById('lblProductDesc').innerHTML+=desc.AdditionalText;
            }else
                document.getElementById('lblProductDesc').innerHTML = '';         
            
            //enable the button - was disabled in multiple places!
            if(_canEnableButton)
            {
                document.getElementById('ctl00_CenterContentPlaceHolder_ucOrderInfoControl_btnAddToShoppingBag').onclick = function()
                {
                    AddToShoppingBag();
                    return false;
                }
            }      
            
    },
    function(error)
    {
    });
}

function AddToShoppingBag()
{
    //call ws, redirect
    Website.WebServices.WebService.AddToShoppingBag(GetCookie(),
    function (result)
    {
        var url='';
        //url rewrite
        if (document.getElementById('ctl00_UrlRewrite').value != '' )
        {
            url = document.getElementById('ctl00_UrlRewrite').value;
        }        
        //redirect!
        //window.location.href = '/shoppingbagPage.aspx' + url;
        window.location.href = '/shoppingbagPage.aspx';
    },
    function(error)
    {
    });
}

function AddToShoppingBagFromCert()
{
   //call ws, redirect
    Website.WebServices.WebService.AddToShoppingBag(GetCookie(),
    function (result)
    {
        window.opener.location.href='/shoppingbagPage.aspx';
        window.close();
    },
    function(error)
    {
    });                

}
function RemoveItemFromBag(uniqueId)
{
    Website.WebServices.WebService.RemoveFromShoppingBag(uniqueId,GetCookie(), 
    function (result)
    {
//        var url = getQuerystring('prevUrl');
//        //redirect!
        window.location.href = '/shoppingbagPage.aspx';
    },
    function(error)
    {
    });
}

function ViewDetailsForItem(uniqueId,itemName,count)
{
    Website.WebServices.WebService.ViewDetailsForItem(uniqueId,GetCookie(), 
    function (result)
    {
        document.getElementById('ctl00_CenterContentPlaceHolder_lblItemSelected_ShoppingBag').innerHTML = '';
        document.getElementById('ctl00_CenterContentPlaceHolder_lblItemSelected_ShoppingBag').innerHTML = 'Item ' + count + ': The ' + itemName;
        document.getElementById('ctl00_CenterContentPlaceHolder_lblItemDetailsContainer').innerHTML = '';
        document.getElementById('ctl00_CenterContentPlaceHolder_lblItemDetailsContainer').innerHTML = result;
    },
    function(error)
    {
    });
}
var intervalLeft;
var xLeft = 0;
function ScrollLeft()
{
    document.getElementById('ctl00_Header_ucTopNav_ulSubMenu').style.left=xLeft+ 'px';
    intervalLeft = setInterval(function()   
    {
        xLeft = xLeft-2;
        document.getElementById('ctl00_Header_ucTopNav_ulSubMenu').style.left=xLeft + 'px';
    },200);
}

function StopScrollLeft()
{
    window.clearInterval(intervalLeft);
}

function DrawFinanceOptions(amount)
{
    amount = amount.replace('£ ','').replace(',','');    
    if (amount>=500 && amount<=5000 )
        addOptionToFinanceDDL(document.aspnetForm.ddlFinanceOptions,'6 Months (0% APR)','ONIF6',false,amount  );
    addOptionToFinanceDDL(document.aspnetForm.ddlFinanceOptions,'12 Months (9.9% APR)','ONIB12-9.9',false,amount);
    addOptionToFinanceDDL(document.aspnetForm.ddlFinanceOptions,'24 Months (19.5% APR)','ONIB24-19.5',false ,amount );
    addOptionToFinanceDDL(document.aspnetForm.ddlFinanceOptions,'36 Months (19.5% APR)','ONIB36-19.5',true,amount );
}

function addOptionToFinanceDDL(selectBox, text, value, isSelected, amount)
{        
    var optn = document.createElement('option');            
    optn.setAttribute('amount',amount);
    optn.text = text;
    optn.value = value;
    optn.selected= isSelected;
    selectBox.options.add(optn);
}

function DrawFinanceInfo()
{
    
    var ddlFinanceOptions = document.getElementById('ddlFinanceOptions');
    var financeValue=ddlFinanceOptions.options[ddlFinanceOptions.selectedIndex].value;
    var amount = ddlFinanceOptions.options[ddlFinanceOptions.selectedIndex].getAttribute('amount');
    
    Website.WebServices.WebService.GetFinanceSummary(amount,financeValue, 
    function(result)
    {       
        var financeInfo = eval('(' + result + ')');
        var finance = financeInfo.SingleObject;
        
        if(finance!=null && finance!=undefined)
        {
            document.getElementById('lblDepositPercent').innerHTML = finance.DepositPercent + '&nbsp;&nbsp;&nbsp;(' + finance.DepositAmount + ')';
            document.getElementById('lblNumberOfPayments').innerHTML = finance.NumberOfMonthlyPayments + '&nbsp;&nbsp;X&nbsp;&nbsp;' + finance.MontlyPayment;
        }
    },
    function(error)
    {
    });
}


function MashAndSelectItem(itm)
{
    var item = eval('(' + itm + ')');
    WriteNameAndSelectInList(item.Name, item.Id);
    var mashedItems = item.MashedItems;
    var container = document.getElementById('mashedItems');
    while (container.childNodes[0])
    {
        container.removeChild(container.childNodes[0]);
    }
    var tbody = document.createElement('tbody');
    container.appendChild(tbody);
    container.style.display = 'block';
    var trContainer = document.createElement('tr');
    tbody.appendChild(trContainer);
    
    //add the label for the mashed items first
    var tdLabel = document.createElement('td');
    tdLabel.className='mashedItemsTagName';
    tdLabel.innerHTML = item.MasherLabel;
    //container.appendChild(tdLabel);
    trContainer.appendChild(tdLabel);
    //create a new table inside a container td in container
    var tdContainer = document.createElement('td');
    trContainer.appendChild(tdContainer);
    
    var table = document.createElement('table');
    table.setAttribute('style','cellPadding:0px; cellSpacing:0px;');
    table.className='mashedItemsContainer';
    tdContainer.appendChild(table);
    var tbodytable  = document.createElement('tbody');
    table.appendChild(tbodytable);
    var tr = document.createElement('tr');
    tbodytable.appendChild(tr);
    
    for(var i=0;i<item.MashedItems.length;i++)
    {
        var td = document.createElement('td');
        
        td.innerHTML = mashedItems[i].MashedNameInLanguage;
        
        if(mashedItems[i].MashedName=='Full')
        {
            td.innerHTML +='<br/><img src=\'../images/filters/full.png\' />';
        }
        else if(mashedItems[i].MashedName=='Half')
        {
            td.innerHTML +='<br/><img src=\'../images/filters/half.png\' />';
        }
        
        if(i==0)
            td.className = 'diamond_control_clarity_select diamond_control_select_bg_selected';
        else
            td.className = 'diamond_control_clarity_select diamond_control_select_bg';
        td.setAttribute('style','width:' + 478/mashedItems.length + 'px');
        td.ItemId = mashedItems[i].MashedItemId;
        td.Parent = table;
        td.Mash = mashedItems[i];
        td.onclick = function()
        {
            var tds = this.Parent.getElementsByTagName('td');
            for(var i=0;i<tds.length;i++)
            {
                if(tds[i].ItemId == this.Mash.MashedItemId)
                {
                    if(tds[i].className != 'diamond_control_clarity_select diamond_control_select_bg_selected')
                    {
                        tds[i].className = 'diamond_control_clarity_select diamond_control_select_bg_selected';
                        SelectMashedItem(this.Mash);
                    }
                }
                else
                {
                    tds[i].className = 'diamond_control_clarity_select diamond_control_select_bg';
                }
            }
        }
        tr.appendChild(td);        
    }
    
    SelectMashedItem(mashedItems[0]);
}

function SelectMashedItem(mashedItem)
{
      xtItemId = mashedItem.MashedItemId;
      itemPreferences.ItemId = xtItemId ; 
      Website.WebServices.WebService.GetItemById(xtItemId, GetCookie(),false, 
     function(success)
     {
        var item = eval('(' + success + ')');
        currentlySelectedItem = item;
        ConfigureSelectedItem(item);
     },
     function(error)
     {  
     });
}
