﻿
/////////////////////////////////////////////////////////////////////
//////// Utility Functions used by JS in this section: START  ///////
/////////////////////////////////////////////////////////////////////

/////////////////////////////////////////
// trim white space on both end of string
//For EBTM Product Page
var imageArray = new Array();
var inventoryArray = new Array();
var StockMessage = new String();

var NOPICTURE = "nopicture";

function GetEmailInStockURL()
{
    var objSize = document.getElementById('Size');
    var objColor = document.getElementById('Color');
    var objStockInAnchor = document.getElementById('EmailStockInAnchor');
    
    var sSize = "";
    var sColor = "";
    var sURL = "";
    
    if (null != objSize)
        sSize = objSize[objSize.selectedIndex].text;
        
    if (null != objColor)
        sColor = objColor[objColor.selectedIndex].text;
    if (null != objStockInAnchor)
    {
        objStockInAnchor.href = objStockInAnchor.href + "&Size=" + escape(sSize) + "&Color=" + escape(sColor);
    }    
        
    return true;
}

function SetStockMessage(sMessage)
{
    StockMessage = sMessage;
}


function setCookie(c_name,value,expiredays)
{
    var exdate=new Date();
    exdate.setDate(exdate.getDate() + expiredays);
    document.cookie=c_name+ "=" +escape(value)+ ((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

function setInventory(bNoOffset)
{
    
    var nColorIndex = -1;
    var nSizeIndex = -1;
    var objDiv = null;
    
    
    objDiv = document.getElementById('ProductInventory');
    if (null == objDiv)
        return;
    
    //This takes care of auto select size option 
    if (bNoOffset)
    {
        nColorOffset = 0;
        nSizeOffset = 1;
    }
    else
    {
        nColorOffset = 1;
        nSizeOffset = 0;
    }
    
    if (document.getElementById('Color'))
    {
        nColorIndex = document.getElementById('Color').selectedIndex;
        var nSelectedColor = document.getElementById('Color').options[nColorIndex].innerHTML;
        objLastClicked = document.getElementById('lastColor');
        if (objLastClicked)
            objLastClicked.Value = nSelectedColor;
    }    
    if (document.getElementById('Size'))
    {
        nSizeIndex = document.getElementById('Size').selectedIndex;
        var nSelectedSize = document.getElementById('Size').options[nSizeIndex].innerHTML;
        objLastClicked = document.getElementById('lastSize');
        if (objLastClicked)
            objLastClicked.Value = nSelectedSize;
    }
    else if (nColorIndex == -1)
        return;
    
    if ((0 == nSizeIndex || 0 == nColorIndex) && bNoOffset)
    {
        objDiv.innerHTML = "";
        return;
    }
    
    var sText = new String();
    
    if (nColorIndex == -1)
        sText = inventoryArray[0][nSizeIndex - nSizeOffset];
    else if (nSizeIndex == -1)
        sText.innerHTML = inventoryArray[nColorIndex + nColorOffset][0];
    else
        sText = inventoryArray[nColorIndex + nColorOffset][nSizeIndex - nSizeOffset];    
        
    objDiv.innerHTML = sText.replace(/%27/g,"'");
    
    //Now make the email in stock visible if the item is not to be displayed
    
    var objStockDiv = document.getElementById('ProductEmailInStock');
    
    if (objStockDiv != null)
    {
        if (StockMessage == objDiv.innerHTML)
            document.getElementById('ProductEmailInStock').style.display = 'none';    
        else
            document.getElementById('ProductEmailInStock').style.display = 'block';    
    }       
    
    return;    
        
        
}

function SetMediumImageSrc(objID, bNoOffset)
{
    var nID = 0;
    var nOffset = 0;
    
    //This takes care of auto select size option 
    if (bNoOffset)
        nOffset = 0;
    else
        nOffset = 1;
    
    if (objID)
        nID = objID.name;
        
    var nSelectedIndex = 0;
    
    if (document.getElementById('Color'))
        nSelectedIndex = document.getElementById('Color').selectedIndex;
    else
        nSelectedIndex = -1;
        
    var objLastClicked = document.getElementById('lastClicked');
    if (objLastClicked)
    {
        objLastClicked.value = nID;  
    }
    
    if (nSelectedIndex > -1)
    {
        document.getElementById('ProductMainImage').src = imageArray[1][nID][nSelectedIndex + nOffset];
    }
    else
    {
        document.getElementById('ProductMainImage').src = imageArray[1][nID][0];
    }
    
    return;     
}

//For Setting(s)
//use 0 - to make Dest = Source
//Use 1 - to make same size as largest
//Use 2 - to make same size as smallest

function matchColumns(idSource, idDest, nSettings)
{

    var divSource = document.getElementById(idSource);
    var divDest = document.getElementById(idDest);
    
    var nSourceHeight = 0;
    var nDestHeight = 0;
        
    if (!divSource || !divDest)
        return;
    
    if(divSource.offsetHeight)
    {
        nSourceHeight = divSource.offsetHeight;
        nDestHeight = divDest.offsetHeight;
    }
    else if(divSource.style.pixelHeight)
    {
        nSourceHeight = divSource.style.pixelHeight;
        nDestHeight = divDest.style.pixelHeight;
    }
    
    switch(nSettings)
    {
        case 0: 
            divDest.style.height = nSourceHeight + "px";
            break;
        case 1:
            if (nSourceHeight > nDestHeight)
            {
                divDest.style.height = nSourceHeight + "px";
                divSource.style.height = nSourceHeight + "px";
            }
            else
                divSource.style.height = nDestHeight + "px";
                divDest.style.height = nDestHeight + "px";
            break;
        case 2:   
            if (nSourceHeight > nDestHeight)
            {
                divSource.style.height = nDestHeight + "px";
                divDest.style.height = nDestHeight + "px";
            }
            else
            {
                divDest.style.height = nSourceHeight + "px";
                divSource.style.height = nSourceHeight + "px";
            }
            break;
    }
    
    return;
}


function createImageGallery(bNoOffset)
{
    var ITEMS_PER_ROW = 3;
    var NO_PICTURE = "nopicture";
    var objNextImage;
    var sGallery = "";
    var nSelectedIndex = 0;
    var objUL = null;
    var objLI = null;
    var objAnchor = null;
    var objImage = null; 
    
   if (document.getElementById('Color'))
        nSelectedIndex = document.getElementById('Color').selectedIndex;
   else
        nSelectedIndex = -1;
        
    var iconGallery = document.getElementById('ProductIconGalleryDiv');
    
    //This takes care of auto select size option 
    if (bNoOffset && -1 != nSelectedIndex)
        nOffset = 0;
    else
        nOffset = 1;
    
    iconGallery.innerHTML = "";
    
    var length = imageArray[0].length;
    
    //We need to centre the last row of the gallery so we will calculate 
    //how many are onj the last row and then space accordingly
    var nNumberOfItemsOnLastRow = length % ITEMS_PER_ROW;
    var sID = "";
   
    objUL = document.createElement("ul");
    objUL.setAttribute("id", "ProductIconGallery");
    objUL.setAttribute("title", "List of possible option for the current size and color");
   
    sGallery = "<ul id=\"ProductIconGallery\" title=\"List of possible option for the current size and color\">";    
    
    var nCount = 0;
    var sMediumImg = "";
    var sIconImg = ""; 
    
    //Count the images in the as we dont need a gallery when there is only 1 image
    for (i = 0; i < length; i++)
    {
        sMediumImg = new String(imageArray[1][i][nSelectedIndex + nOffset]);
        if (sMediumImg.indexOf(NO_PICTURE) == -1 )
            nCount++;
    }
    //Don't draw a gallery if there is only 1 - pointless
    if (nCount < 2)
        return;
        
    for (i = 0; i < length; i++)
    {   
       
        objLI = document.createElement("li");
        objUL.appendChild(objLI);
        
        objAnchor = document.createElement("a");
            
        objAnchor.setAttribute("id", "GalleryAnchor" + i );
        objAnchor.setAttribute("title", "Click to show the medium size image" );
        objAnchor.setAttribute("href", "#" );
        objAnchor.setAttribute("name", i);
        if (document.attachEvent){
            if (bNoOffset)
                objAnchor['onclick'] = function(){SetMediumImageSrc(this,true)};
            else
                objAnchor['onclick'] = function(){SetMediumImageSrc(this,false)};
        }
        else if (document.addEventListener) 
        {
            if (bNoOffset)
                objAnchor.addEventListener('click', function(){ SetMediumImageSrc(this,true);}, false);
            else
                objAnchor.addEventListener('click', function(){ SetMediumImageSrc(this,false);}, false);
        }
 
        sMediumImg = new String(imageArray[1][i][nSelectedIndex + nOffset]);
        sIconImg = new String(imageArray[0][i][nSelectedIndex + nOffset]);
        if ((typeof(sIconImg) == "undefined" || sIconImg.indexOf(NO_PICTURE) != -1) && sMediumImg.indexOf(NO_PICTURE) == -1 )
        {
            objAnchor.appendChild(document.createTextNode("[" + (i + 1) + "]"));       
        }
        else if (typeof(imageArray[0][i][nSelectedIndex + nOffset]) != "undefined" && sMediumImg.indexOf(NO_PICTURE) == -1 )
        {
            objImage = document.createElement("img");
            objImage.setAttribute("id", "GalleryImage");
            objImage.setAttribute("src", imageArray[0][i][nSelectedIndex + nOffset]);
            objAnchor.appendChild(objImage);
        } 
        
        objLI.appendChild(objAnchor);                  
        
    }
    
    iconGallery.appendChild(objUL);
    return;
    
}


function ShowLargeImage(nOffset)
{ 
    var LARGEIMAGEINDEX = 2;
    var LARGEIMAGEINDEX = 2;
    var objLastClicked = document.getElementById('lastClicked');
    var objColor = document.getElementById('Color');
    var nSelectedIndex = -1;
    
    if (objLastClicked)
    {
        if (objColor)
            nSelectedIndex = document.getElementById('Color').selectedIndex;
        
        popupimg(imageArray[LARGEIMAGEINDEX][objLastClicked.value][nSelectedIndex + nOffset]);
        
        
    }
    
    return;    
}



function popupimg(url)
{
    var NOPICTURE = "nopicture";
    
    
    if (typeof(url) == "undefined" || url.indexOf(NOPICTURE) != -1)     
    {
        alert("There is currently no matching large image for this image");
        return;       
    }
    
    window.open('popup.aspx?src=' + url,'','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,copyhistory=no,width=449,height=449,left=0,top=0');
    return;
}

function popupTopic(sTopic)
{
   window.open('popup.aspx?Topic=' + sTopic,'','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,copyhistory=no,width=800,height=600,left=0,top=0');
            
    
}

function trim(varString)
{
    var strBuffer = "";
    var strTrimmed = "";
    
    if(varString==null || varString=="undefined")
        return "";
    
    if(varString.length==0)
        return "";

     for(var i=0;i<varString.length;i++)
    {
        strBuffer = varString.substring(i,i+1);
        
        if(i==0 && strBuffer == " ")
            continue;
        else if(i==varString.length-1 && strBuffer == " ")
            continue;
        else
            strTrimmed += strBuffer;
    }        
    
    return strTrimmed;   
}

function removeSpace(varString)
{
    var strBuffer = "";
    var strTrimmed = "";
    
    if(varString==null || varString=="undefined")
        return "";
    
    if(varString.length==0)
        return "";

     for(var i=0;i<varString.length;i++)
    {
        strBuffer = varString.substring(i,i+1);
        if(strBuffer != " ")
            strTrimmed += strBuffer;
    }        
    
    return strTrimmed;   
}
/////////////////////////////////////////////////////////////////////
//////// Utility Functions used by JS in this section: END    ///////
/////////////////////////////////////////////////////////////////////


/////////////////////////////////////////////////
// QAS Integration: Quick Address
// ----------------------------------------------
function popUpQuickAddress(arrInputIDs,path){
	var url = path+"?inputs="+arrInputIDs;

	var popUp = window.open(url,"QuickAddress","width=700,height=360,scrollbars=no;resizable");
	popUp.focus(); 
	return false;
}


/////////////////////////////////////////////////
// functions used by Search By Brand/Band/Keyword
// ----------------------------------------------

function mag_searchby(optItem, frm)
{
    var nID;
    var strID="";
    var strBuffer="";
    var strError="";
    var theOptionSelected;
    var strOptionText="";
    var strSEPrefix="";
    var strAction="";

    if(optItem==null ||optItem=="undefined")            
    {
        strError = "Unknown error for Band/Brand search, please contact support.";
        alert(strError);
        return false;
    }
    
    if(optItem.selectedIndex==0)
    {
        strError = "Please select from the dropdown list.";
        alert(strError);
        optItem.selectedIndex=0;
        optItem.focus();
        return false;
    }
       
    theOptionSelected = optItem.options[optItem.selectedIndex];
    
    if(optItem.selectedIndex==0)
    {
        strError = "Please select from the dropdown list.";
        alert(strError);
        optItem.selectedIndex=0;
        optItem.focus();
        return false;
    }    
		    
//    nID = theOptionSelected.value;
//    
//    // trim the value in case empty value encountered
//    strID = removeSpace(nID);
//    
//    if(strID.length == 0)
//    {   
//        strError = "Unknown error for '" + theOptionSelected.text + "'.";
//        strError += "\n\nPlease choose another one or contact support.";
//        alert(strError);
//        optItem.focus();
//        return false;
//    }
//    
//    // trim the value in case empty value encountered
//    strOptionText = removeSpace(theOptionSelected.text);

//    if(strOptionText.length == 0)
//    {   
//        strError = "Unknown error for selection [IndexID=" + optItem.selectedIndex + "].";
//        strError += "\n\nPlease choose another one or contact support.";
//        alert(strError);
//        optItem.focus();
//        return false;
//    }
//    else
//    {
//        /* 
//        Two replace() called can be done in one go, but white space would be   
//        hardly visible in pattern, so do it explicitly in second replace call
//        */
//        //do global & case insensitive replace for invalid chars - excluding white space
//        strOptionText = strOptionText.replace(/[^0-9a-z_]/gi, '-');
//        //do global & case insensitive replace - for white space only
//        strOptionText = strOptionText.replace(/ /gi, '-'); 
//    }
//    
//    if(frm==document.forms[0])
//        strSEPrefix = "g";
//    else if(frm==document.forms[1])
//        strSEPrefix = "m";
//    else
//    {
//        strError = "Unknown form error for '" + frm.name + "'.";
//        strError += "\n\nPlease contact support.";
//        optItem.focus();
//        return false;
//    }
//    
//    strAction = strSEPrefix + "-" + strID + "-" + strOptionText + ".aspx"

		strAction = theOptionSelected.value;
    window.top.location = 
    frm.action = strAction;
    frm.submit();    
    
}

function mag_focussearchkeyword(obj)
{
    if(obj.value.toLowerCase()=="by keyword")
        obj.value = "";
    
}

function mag_searchkeyword(obj)
{
    var strBuffer="";
    var strError="";
    if(obj==null ||obj=="undefined")
    {
        strError = "Unknown error for Keyword search, please contact support.";
        alert(strError);
        return;    
    }
    strBuffer = obj.value;
    strBuffer = strBuffer.toLowerCase();
    if(strBuffer=="by keyword")
        obj.value = "";
    
}

function mag_submitOnEnter(e,form,buttonToClick)
{
    var keynum = 0;
    if(e.keyCode) // IE
    {
    keynum = e.keyCode
    }
    else if(e.which) // Netscape/Firefox/Opera
    {
    keynum = e.which
    }
    if(keynum == 13){
    document.forms[form][buttonToClick].click();
    }
}



/////////////////////////////////////////////////
// functions used by Nisbets' Submit Orders to RB site
// ----------------------------------------------

function mag_popUp(url, name, width, height){
	var popUp = window.open(url,name,"width="+width+",height="+height+",scrollbars=yes,resizable=yes,status=yes");
	popUp.focus(); 
	return false;
}
function mag_showSendOrder(orderNumber){
	var url = "SendOrder.aspx?OrderNumber="+orderNumber;
	return mag_popUp(url,"SendOrder",800,600);
}
function mag_showOrderResponse(orderNumber){
	var url = "SendOrderResponse.aspx?OrderNumber="+orderNumber;
	return mag_popUp(url,"SentOrder",800,600);
}

/////////////////////////////////////////////////
// functions used by TRAIDCRAFT'
// ----------------------------------------------

/*
function enlarge()
{
    var elem = document.getElementById('ProductSelect');
    if (elem)
    {
        //get the current selection
        var npos = elem.selectedIndex;
        //get the current product selected
        var nproductid = elem.options[npos].value;

        var lastClick = document.getElementById('hdnLastClicked');
        if ( lastClick )
        {
            var index = lastClick.value;
            var imgUrl = eval ('imageArray_' + nproductid + '[2][' + index + '][0]')
            popupimg(imgUrl);
        }
    }
}
*/

function enlarge()
{
    var elem = document.getElementById('MainImage');
    
    if (elem)
    {
        var url = elem.src;

        url = escape(url.replace("/medium/", "/large/"));

        popupimg(url);
    }
}    
function showzoom(imgURL)
{
    var mainImage = document.getElementById('MainImage');
    var prodSel = document.getElementById('ProductSelect');
    var quanBox = document.getElementById('Quantity');
    
    if (mainImage && (prodSel || quanBox))
    {
        if (mainImage.src.indexOf(NOPICTURE) != -1)
        {
            alert('There is no zoom image for this product');
            return;
        }
        
        var sID;
        var skuVal;
        
        if (prodSel)
        {   
            var nSelected = prodSel.selectedIndex;
            var nValue = prodSel.options[nSelected].value;
            sID = 'SKU_' + nValue;
            skuVal = document.getElementById(sID);
        }
        else if (quanBox)
        {
            skuVal = document.getElementById('SKU');
        }
        else
            return;
            
        if (skuVal)
        {
            var npos = imgURL.lastIndexOf('.');
            var sExtension = imgURL.substring(npos);
            
            var npos2 = imgURL.lastIndexOf('swatch');
            imgURL = imgURL.substring(0, npos2);
            imgURL = imgURL + 'swatch/' + skuVal.value + sExtension;   
        }
        
        window.open('ImageZoom.aspx?img=' + imgURL,'','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,copyhistory=no,width=750,height=420,left=0,top=0');
        
    }
}

function submitForm(form)
{

    var elem = document.forms[1];
    if (elem)
    {
        if (!formValidator(elem))
        return false;

        if (validateForm(elem))
        {
            elem.submit();
            return true;
        }
        else
            return false;
    }
}

function changeMedImage(number)
{
  if (number >= 0)
  {
    //first set the last clicked
    var lastClick = document.getElementById('hdnLastClicked');
    if (lastClick)
    {
      lastClick.value = number;
    }
    var sel = document.getElementById('ProductSelect');
    if (sel)
    {                   
      var productid = sel.options[sel.selectedIndex].value;
    
      var elem = document.images['MainImage'];
      if (elem)
      {
        var arrayString = 'imageArray_' + productid + '[1][' + number + '][0]';
        elem.src = eval(arrayString);
      }
    }
    else
    {
			// Also allow images to be changed on the product page.
			sel = document.getElementById('MainImageProductID');
			if (sel)
			{
				var productid = sel.value;
	    
				var elem = document.images['MainImage'];
				if (elem)
				{
					var arrayString = 'imageArray_' + productid + '[1][' + number + '][0]';
					elem.src = eval(arrayString);
				}
			}
    }
  }
}

function getElementsByClass(searchClass,node,tag) 
{	
    var classElements = new Array();
    if ( node == null )
    		node = document;	
    if ( tag == null )		
        tag = '*';	
    var els = node.getElementsByTagName(tag);	
    var elsLen = els.length;	
    var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");	
    
    for (i = 0, j = 0; i < elsLen; i++) 
    {		
        if ( pattern.test(els[i].className) ) 
        {			
            classElements[j] = els[i];			
            j++;		
        }	
    }	
    
    return classElements;
}

function setRadio(row)
{
    var radioButtons = null;
    var listItems = null;
    var firstItem = document.getElementById('ZeroDonation');
    
    if (row == null && firstItem)
    {
        row = firstItem;
    }         
            
    radioButtons = getElementsByClass('rbDonation', row, 'input');
    listItems = getElementsByClass('liDonation', document.getElementById('DonationsList'), 'li');
    
    if (radioButtons && radioButtons[0])
    {
        radioButtons[0].checked = true;
    }
    
    var nCount = listItems.length;
    var elem = document.getElementById('GiftAid');
    
    for (i = 0; i < nCount; i++)
    {
        if (listItems[i] == row)
        {
            if (elem)
            {
                if (i == 0)
                {
                    var elem2 = document.getElementById('GiftForLifeField');
                    
                    if (elem2)
                    {
                        if (elem2.value == 0)
                            elem.style.display = 'none';
                        else
                            elem.style.display = 'block';
                    }
                }
                else
                {
                    elem.style.display = 'block';
                }
            }
                
            listItems[i].style.backgroundColor = '#F2F2E6';
        }
        else
            listItems[i].style.backgroundColor = '#ffffff';
    }
    
    setTotals(row);
}

function setTotals(row)
{

    var sTotalDonation = 0;
    
    if (row == null)
        return;
        
    //look for the class(right) to grab the value
    var spans = getElementsByClass('right', row, 'span');
    
    //Text box value
    var txtBox = getElementsByClass('Donator',row,'input' );
    
    //Select box value
    var selectBox = getElementsByClass('SelectDon',row,'select' );
    
    
    //else grab the textbox
    if (txtBox.length > 0)
    {
         txtBox = txtBox[0];
         if (txtBox)
            sTotalDonation = txtBox.value;
            
         if (sTotalDonation.length > 1)
            sTotalDonation = sTotalDonation.substring(1);
    
    }
    else if (selectBox.length > 0)
    {
        selectBox = selectBox[0];
        if (selectBox)
            sTotalDonation = selectBox[selectBox.selectedIndex].value        
    }    
    //If exists
    else if (spans && spans[0])
    {
        sTotalDonation = spans[0].innerHTML;
        sTotalDonation = sTotalDonation.substring(1)
    }
    
        
    //Find the order subtotal
    var ordertotal = document.getElementById('OrderTotal').innerHTML;
    ordertotal = ordertotal.substring(1);
    
    //find the target dubtotal
    var subtotal = document.getElementById('spSubtotal');
    if (subtotal)
        subtotal.innerHTML = formatCurrency(sTotalDonation);
    
    //find the target total
    var total = document.getElementById('spTotal');
    if (total)
        total.innerHTML = formatCurrency(parseFloat(sTotalDonation) + parseFloat(ordertotal));
    //poulate hidden feilds for basket
    var pid = document.getElementById('ProductID');
    var amt = document.getElementById('Price'); 
    
    if (amt)
        amt.value = sTotalDonation;
    
    return;
}

function FormatFreeBox(box)
{
    var formattedValue = formatCurrency(box.value);
    box.value = formattedValue;
    
    var elem = document.getElementById('FreeFormLI');
   
    if (elem != null)
    {
        setTotals(elem);
    }
    
}

function formatCurrency(num) 
{
    num = num.toString().replace(/\£|\,/g,'');
    if(isNaN(num))
        num = "0";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num*100+0.50000000001);
    cents = num%100;
    num = Math.floor(num/100).toString();
    if(cents<10)
        cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
        num = num.substring(0,num.length-(4*i+3))+ ',' + num.substring(num.length-(4*i+3));
    return (((sign)?'':'-') + '£' + num + '.' + cents);
}

function checkGiftAid()
{
    var elemDiv = document.getElementById('GiftAid');
    if (elemDiv)
    {
        //If hidden we dont need to bother
        if (elemDiv.style.display == 'none') 
            return true;
        else
        {
            var elemRadio1 = document.getElementById('rblGiftAid_0');
            var elemRadio2 = document.getElementById('rblGiftAid_1');
            
            if (elemRadio1 && elemRadio2)
            {
                if (elemRadio1.checked || elemRadio2.checked)
                    return true;
                    
                return false;
            }
        }
            
    }
    return false;
}

function checkTotalsBeforeSubmit()
{
    var totalField = document.getElementById('spTotal');
    
    var bGiftAid = checkGiftAid();
    
    if (!bGiftAid)
        return false;
           
 
    if (totalField )
    {
        var total = totalField.innerHTML;
        total = total.substring(1);
         
        if (total.length == 0 || isNaN(total) || parseInt(total) < 0)
            return false;
        
        return true;
    }
    
    return;

}

//Check all medium images for the _ decoration that assumes we have an imageArray
//this is used to determine if we are in a 
function checkArray(arr, totalImages)
{
    for (i = 0; i < totalImages; i++)
    {
        var item = arr[1][i][0];
        
        if (item)
        {
            if (item.indexOf('_.') != -1 )
            {
                 return false;      
            }
        }
    }
    
    return true;
}

function changeImages(totalImages)
{
		var j = 0;
    var NOPICTURE = "nopicture";

    var clickElem = document.getElementById('hdnLastClicked');
    var itemClicked = 0;
   
    var elem = document.getElementById('ProductSelect');
    var elem2 = document.getElementById('Quantity');
    if (elem || elem2)
    {   
        var productid;
        if (elem)
        {
            var npos = elem.selectedIndex;
            productid = elem.options[npos].value;
        }
        else
        {
            var prod = document.getElementById('ProductID');
            if (prod)
                productid = prod.value;
        }
            
        var arrayToUse = eval('imageArray_' + productid);
        
        var bUseEntityImage = checkArray(arrayToUse, totalImages);
        
        var mainImage = document.getElementById('MainImage');
        
        var newsrc;
        
        if (mainImage)
        {
            if (bUseEntityImage)
                newsrc =  arrayToUse[1][0][0];                    
            else
            {   
                var nextItem = "";
                for (i = 0; i < totalImages; i++)
                {
                    nextItem = arrayToUse[1][i][0];
                    if (nextItem.indexOf(NOPICTURE) == -1)
                    {
                        //Now check there is a matching icon image and only show main image if true
                        if (arrayToUse[0][i][0].indexOf(NOPICTURE) == -1)
                        {
                            newsrc = nextItem;
                            break;
                        }
                    }   
                }
            }
            
            mainImage.src = newsrc;
            
            //now do the image gallery
            var nTotalImages = totalImages;
            var nextImage;
            
            for (i = 0; i < nTotalImages; i++)
            {
							if (arrayToUse[0][i][0].indexOf(NOPICTURE) == -1)
								j++;
            }
                
            for (i = 0; i < nTotalImages; i++ )
            {
                //get the next images
                var imagename = 'imgGallery_' + i;
                nextImage = document.images[imagename];
                if (nextImage)
                {
                  var src = arrayToUse[0][i][0];
                  if (src.indexOf('nopicture') != -1)
                      nextImage.style.display ='none';
                  else
                  {
											if (j > 1)
												nextImage.style.display = 'inline';
											else
												nextImage.style.display ='none';
                  }  
                  nextImage.src = arrayToUse[0][i][0];
                }
            }
        }
    }
}
