var MainMenuItem, SubMenuItem, OptionsMenuItem, message, CurrentThumbnailSetSize;
ToFadeDB = new Array();
CurrentThumbnailSet = new Array();
FadingTimeout=new Array();
var UnFading = false;

// how much companies maximum to show at companys bar at once (companies per page)
max_companies = 30;

function MainMenuClick(ClickedItem,MenuName)
{
    //reseting SubMenuItem to enable Fade effect on icons.
    SubMenuItem=''; 

    //main menu reset
    ResetMenuItem('services');
    ResetMenuItem('project');
    ResetMenuItem('studio');
    ResetMenuItem('case_study');
    ResetMenuItem('contact');
    
    //projects submenu reset
    ResetMenuItem('concept');
    ResetMenuItem('logotype');
    ResetMenuItem('identity');
    ResetMenuItem('packaging');
    ResetMenuItem('fashion');
    
    HighlightMenuItem(ClickedItem);
    document.getElementById('options1').style.visibility='hidden';//display='none';
    if (MenuName) 
    { 
        document.getElementById(MenuName).style.display='inline';
    }
    MainMenuItem=ClickedItem;

    if (ClickedItem!='project') 
    { 
        document.getElementById('projectsmenu').style.visibility='hidden';//.display='none';
        document.getElementById('arrow_by_date').style.visibility='hidden';
        document.getElementById('arrow_by_brand').style.visibility='hidden';
        document.getElementById('companysbar').innerHTML='';
    } else {
        document.getElementById('projectsmenu').style.visibility='visible';//.display='none';
    }

    /* must be before GenerateXContent in order to allow it's own logic 
       or generate_content.php's logic to overwrite our decisions */
    document.getElementById('catalogs_frame').style.display='none';
    document.getElementById('bigdaddy').style.display='block';
    document.getElementById('copyright').style.display='block';

    switch (ClickedItem)
    {
        case "project":
            GenerateProjectsThumbs('project'); 
            OptionsMenuClick('by_date'); 
            break;
            
        case "contact":
            GenerateContactContent();
            break;

        case "services":
            GenerateServicesContent();
            break;

        case "studio":
            GenerateStudioContent();
            break;

        case "case_study":
            GenerateCaseStudyContent();
            break;
    }

    //document.getElementById('bigdaddy').innerHTML=''; /* don't show old content */
}

function SubMenuClick(ClickedItem) 
{
    ResetMenuItem('concept');
    ResetMenuItem('logotype');
    ResetMenuItem('identity');
    ResetMenuItem('packaging');
    ResetMenuItem('fashion');
    HighlightMenuItem(ClickedItem);
    SubMenuItem=ClickedItem;
    if (MainMenuItem == 'project') 
    { 
        FilterProjectsByType(ClickedItem); 
        UpdateCompanysBar(ClickedItem,OptionsMenuItem);
    }
    OptionsMenuClick('by_date');

    document.getElementById('catalogs_frame').style.display='none';
    document.getElementById('bigdaddy').style.display='block';
    document.getElementById('copyright').style.display='block';
}

function OptionsMenuClick(ClickedItem)
{
    ResetMenuItem('by_brand');
    ResetMenuItem('by_date');
    OptionsMenuItem=ClickedItem;
    HighlightMenuItem(ClickedItem);
    UpdateCompanysBar(SubMenuItem,ClickedItem);
    document.getElementById('options1').style.visibility='visible'//.display='inline'; // old value was .display='';
}


function HighlightClickedLineNameAndOpenLineBelow(comid,lineid) 
{
    for (i = 0; i < LinesTable.length; i++) 
    {
        if (LinesTable[i][1]==comid) 
        {
            if (isset(document.getElementById('line'+lineid)))
            {
                document.getElementById('line'+LinesTable[i][0]).style.color="#AAAAAA";
            }
        }
    }

    if (isset(lineid))
    {
        if (isset(document.getElementById('line'+lineid)))
        {
            document.getElementById('line'+lineid).style.color="#3D3D3D";
        }
    }
    window.frames['transport'].window.location='generate_content.php?brand_ID='+lineid;
}

function ShowCompanyNameAndItsLines(comid, is_catalog_mode, picture_path, requested_line_id) 
{
    additional_flags='';
    if (is_catalog_mode)
    {
        additional_flags+="&mode=catalog";
    }

    if (isset(picture_path))
    {
        additional_flags+="&picture_path="+picture_path;
    }

    // Showing Company Name
    for (i = 0; i < CompanysTable_byDate.length; i++) 
    {
        if (CompanysTable_byDate[i][0]==comid) 
        { 
            CompanysBarContent='<span style="color:black; font-weight:bold;">'+CompanysTable_byDate[i][1]+'</span><br>'; 
        }
    }

    // Showing Company Lines
    lineid=''; // in case there is no lines at all for this brand, lineid will be undefined
    Separator='';
    for (i = 0; i < LinesTable.length; i++) 
    {
        if (LinesTable[i][1]==comid) 
        {
            CompanysBarContent=CompanysBarContent+Separator+'<span style="cursor:pointer;" id="line'+LinesTable[i][0]+'" onclick="HighlightClickedLineNameAndOpenLineBelow('+comid+','+LinesTable[i][0]+');">'+LinesTable[i][2]+'</span>';
            // If this is first line then open it on pain page
            if (Separator=='') 
            {
                lineid=LinesTable[i][0];
                if (isset(requested_line_id))
                {
                    lineid=requested_line_id;
                }
                window.frames['transport'].window.location='generate_content.php?brand_ID='+lineid+additional_flags;
            }
            Separator=' / ';
        }
    }

    document.getElementById('companysbar').innerHTML = CompanysBarContent;
    
    if (isset(lineid))
    {
        if (isset(document.getElementById('line'+lineid)))
        {
            document.getElementById('line'+lineid).style.color="#3D3D3D";
        }
    }
}

function UpdateCompanysBar(filterbytype, sortby, offset) 
{
    if (!isset(offset))
    {
        offset=0;
    }

    // default case, we'll change it if filterbytype==fashion
    is_catalog_mode=false;
    if (filterbytype!="") 
    {
        switch(filterbytype)
        {
            case "concept":     
                typeid=3;  
                break;

            case "identity":    
                typeid=4;  
                break;

            case "packaging":   
                typeid=5;  
                break;

            case "logotype":    
                typeid=6;  
                break;

            case "fashion":     
                typeid=7; 
                is_catalog_mode=true;  
                break;
        }
    
        //Now we are moving thru LINES(LinesTable) array and recording CompanyIDs with requested typeid
        FilteredCompanys = new Array();
        for (i = 0; i < LinesTable.length; i++) 
        {
            if (LinesTable[i][typeid]==1) 
            {
                //Setting "1" for CompanyID in FilteredCompanys, which mach filter criteria
                FilteredCompanys[LinesTable[i][1]]=1; 
            } 
        }
    }

    // points to array according to current filter (CompanysTable_byDate for by_date filter and CompanysTable_byName for by_brand)
    var CurrentFilterArray;
    switch (sortby)
    {
        case 'by_date':
            CurrentFilterArray=CompanysTable_byDate;
            break;
        case 'by_brand':
        default:
            CurrentFilterArray=CompanysTable_byName;
            break;
    }

    // no need to show prev button if we don't have an offset (we are at start of line)
    CompanysBarContent='';
    if (offset>0)
    {
        // if no filter was used, it's simple, just decrease max_companies and you'll get first element at prev page
        if (filterbytype=="")
        {
            prev_page_offset = offset - max_companies;
            have_prev_companies=true;
        } else {
        // in case of used filter, we can't count on offsets at array, we have to check that at block
        // we've left we have at least one company that matchs current filter (so we can print '<prev')
            match_companies=0; last_matched=0;
            for (i = offset; match_companies<=max_companies; i--) 
            {
                if (FilteredCompanys[CurrentFilterArray[i][0]]==1) 
                { //If this company is in Filtered list then count it.
                    match_companies++;
                    last_matched=i;
                }

                if (i==0)
                {
                    break;
                }
            }

            // first match is always a match from page we've got here, we don't count it
            if (1==match_companies)
            {
                have_prev_companies = false;
            } else {
                have_prev_companies = true;
            }

            prev_page_offset=last_matched;
        }

        if (prev_page_offset<0)
        {
            prev_page_offset=0;
        }
        if (have_prev_companies)
        {
            CompanysBarContent=CompanysBarContent+' <a href="#" onclick="UpdateCompanysBar(\'' + filterbytype +'\', \''+sortby+'\', \'' + prev_page_offset + '\')">< ... prev</a> / ';
        }
    }

    showed_companies=0;
    Separator='';
    for (i = offset; showed_companies<=max_companies-1; i++) 
    {
        if (filterbytype=="" || FilteredCompanys[CurrentFilterArray[i][0]]==1) 
        { //If this company is in Filtered list then dosplay it.
            CompanysBarContent=CompanysBarContent+Separator+'<span style="cursor:pointer;" id="company'+CurrentFilterArray[i][0]+'" onclick="ShowCompanyNameAndItsLines('+CurrentFilterArray[i][0]+','+is_catalog_mode+');"> '+CurrentFilterArray[i][1].toUpperCase()+'</span> ';
            Separator=' / ';
            showed_companies++;
        }

        if (i>=CurrentFilterArray.length-1)
        {
            break;
        }
    }

    last_scanned = i;
    have_more = false;

    // decide if we need to paint 'next>'
    if (last_scanned<CurrentFilterArray.length-1)
    {
        if (filterbytype=="")
        {
            have_more = true;
            last_shown = last_scanned;
        } else {
            // check that at rest piece of CurrentFilterArray we actually have at least 1 company that matching filtered criteria
            for (i=last_scanned; i<CurrentFilterArray.length; i++)
            {
                // found first matching object, no need to scan more
                if (FilteredCompanys[CurrentFilterArray[i][0]]==1)
                {
                    have_more = true;
                    last_shown = last_scanned;
                    break;
                }
            } 
        }
    }

    if (have_more)
    {
        CompanysBarContent=CompanysBarContent+'/'+' <a href="#" onclick="UpdateCompanysBar(\'' + filterbytype +'\', \''+sortby+'\', \'' + last_shown + '\')"><nobr>next... ></nobr></a>';
    }

    //alert(CompanysBarContent);
    document.getElementById('companysbar').innerHTML = CompanysBarContent;
}//end of UpdateCompanysBar function


function GenerateStudioContent()
{
    window.frames['transport'].window.location='generate_content.php?mode=studio&brand_ID=20';
}

function GenerateCaseStudyContent()
{
    window.frames['transport'].window.location='generate_content.php?mode=case_study&brand_ID=21';
}

function GenerateServicesContent()
{
    
    document.getElementById('bigdaddy').innerHTML = '<img src="/portfolio/images/services.jpg">';
}

function GenerateContactContent()
{
    ContactsContent='<table border="0" cellpadding="0" cellspacing="0" width="944" height="354"><TR>';
    ContactsContent=ContactsContent+'<td width="731" align="left" valign="top">';
    ContactsContent=ContactsContent+'<img width="731" height="354" border="0" src="images/contact-map.gif"></td>';
    ContactsContent=ContactsContent+'<td width="213" valign="top" height="100%"><table width="213" height="100%" border="0" cellpadding="0" cellspacing="0">';
    ContactsContent=ContactsContent+'<tr style="font-size:11px; font-family:verdana; color:#DDDDDD;"><td width="188" valign="top" BGCOLOR="#2A2A2A">';
    ContactsContent=ContactsContent+'<img src="images/contact.gif" border="0" hspace="0" vspace="0" alt="Please contact David Gurfinkel. Studio\'s Tel: Tel: +972-3-6868086, Fax: +972-3-6868087, Marmorek 9 St. Tel Aviv, ZIP Code: 64254">';
    //ContactsContent=ContactsContent+'<b>Please contact</b><img height="52" width="142" src="images/email5.gif" alt="Guidelines how to get to Gurfinkel Studio LTD. (visual map)" border="0" hspace="0" vspace="0"><br>Studio<br>Tel: +972-3-6868086<br>Fax: +972-3-6868087<br><br>Marmorek 9 St. Tel Aviv,<br>64254<br />';
    ContactsContent=ContactsContent+'</TD></TR></table></td></tr></table>';
    document.getElementById('bigdaddy').innerHTML = ContactsContent;
}

function GenerateProjectsThumbs(flag)
{
    if ('project'==flag)
    {
        CurrentThumbnailSet=ProjectsThumbnailSet1; //;
    }

    /*
    for (i=CurrentThumbnailSet.length; i<24; i++)
    {
            // moved to loop because we want to change elementID (dummy[0]) so we can't referance to same element
            // padd ThumbnailSet with spaces
            dummy = new Array(5);
            dummy[0] = -i //We can't relay on that all id's are sequential! //i;       // elementID used for fading, should be counter of element at array
            dummy[1] = '-1';    // company ID
            dummy[2] = '-1';    // line ID
            dummy[3] = 'is_blank'; // category type, we've created new category is_blank as is_logotype, is_concept, etc
            dummy[4] = '/images/gray_sml_02.gif'; // full path to image that should be shown at images grid
            CurrentThumbnailSet.push(dummy);
    } */

    CurrentThumbnailSetSize=CurrentThumbnailSet.length;
    CurrentThumbnailSet.shuffle();

    /* it will be always 24 objects,*/
    /*CurrentThumbnailSetSize=24; /* CurrentThumbnailSet.length = 24 always */
    //CurrentThumbnailSet.shuffle();

    ShowThumbsFromCurrentThumbnailSet();
}

function ShowThumbsFromCurrentThumbnailSet()
{
    //alert('ShowThumbsFromCurrentThumbnailSet');
    //alert('CurrentThumbnailSetSize=' +CurrentThumbnailSetSize);
    //alert('CurrentThumbnailSet='+CurrentThumbnailSet);
    debugMsg='';
    ThumbsContent = '';
    for (i=0;i<=CurrentThumbnailSetSize-1;i++)
    {
        // we fade only at projects without specified subcategory
        if ("is_blank"==CurrentThumbnailSet[i][3])
        {
            FadeOrNot='';
        } else {
            FadeOrNot='onMouseOver="FadeUnneededIcons(\''+CurrentThumbnailSet[i][3]+'\',\''+CurrentThumbnailSet[i][2]+'\');" onMouseOut="UnFadeAllIcons();"'; 
        }

        // does we should show real image or we have dummy placeholder of plain image
        if ("is_blank"!=CurrentThumbnailSet[i][3])
        {
            ThumbsContent = ThumbsContent + '<a href="#" onClick="ShowCompanyNameAndItsLines(\''+CurrentThumbnailSet[i][1]+'\',false,\''+CurrentThumbnailSet[i][4]+'\','+CurrentThumbnailSet[i][2]+');"><img width="118" height="118" src="'+CurrentThumbnailSet[i][4]+'" border="0" id="'+CurrentThumbnailSet[i][0]+'" '+FadeOrNot+'></a>';
        } else {
            ThumbsContent = ThumbsContent + '<img width="118" height="118" src="'+CurrentThumbnailSet[i][4]+'" border="0" id="'+CurrentThumbnailSet[i][0]+'">';
        }
        if (i==7 || i==15) {ThumbsContent = ThumbsContent + '<br>\n';}
    }
    document.getElementById('bigdaddy').innerHTML = ThumbsContent;
    //document.getElementById('copyright').style.display='block';
}

function FilterProjectsByType(SortType)
{
    
    switch(SortType)
    {
        case "concept":
            CurrentThumbnailSet=ConceptThumbnailSet;
            break;

        case "identity":
            CurrentThumbnailSet=IdentityThumbnailSet;
            break;

        case "packaging":
            CurrentThumbnailSet=PackagingThumbnailSet;
            break;

        case "logotype":
            CurrentThumbnailSet=LogotypeThumbnailSet;
            break;

        case "fashion":
            CurrentThumbnailSet=FashionThumbnailSet;
            break;
    }

    GenerateProjectsThumbs('');
}

function isset(variable)
{
    var undefined;
    return ( variable == undefined ? false : true );
}

function ResetMenuItem(ItemName)
{
    document.getElementById(ItemName).style.color="#7C7C7C";
    document.getElementById(ItemName).style.fontWeight="normal";
    document.getElementById(ItemName).style.fontSize="9px";

    var element_name = 'arrow_'+ItemName;
    element = document.getElementById(element_name);
    if (isset(element))
    {
        element.style.visibility="hidden";
    }
}

function HighlightMenuItem(ItemName)
{
    document.getElementById(ItemName).style.color="#000000";
    document.getElementById(ItemName).style.fontWeight="bold";
    document.getElementById(ItemName).style.fontSize="10px";

    element_name = 'arrow_'+ItemName;
    element = document.getElementById(element_name);
    if (isset(element))
    {
        element.style.visibility="visible";
    }
}

function setOpacity(elementid,level) 
{
  // do not continue to fade if we are at unfading mode
  if (UnFading && level!=1)
  {
    DebugPrint('setOpacity('+elementid+','+level+'): decided not to fade because we are at unfading mode! ');
    return;
  }

  // checking for bugs!
  if (!isset(elementid)) 
  { 
    return; 
  }

  var element = document.getElementById(elementid);
  if (!isset(element)) 
  {
    //alert('Can not find element with id=' + elementid + ', tryied to set level='+level); 
    return;
  }

  document.getElementById(elementid).style.opacity = level;
  document.getElementById(elementid).style.MozOpacity = level;
  document.getElementById(elementid).style.KhtmlOpacity = level;
  document.getElementById(elementid).style.filter = "alpha(opacity=" + (level * 100) + ");";
}

function FadeUnneededIcons(ToKeep,lineid) 
{
    DebugPrint('FadeUnneededIcons(' + ToKeep + ',' + lineid+ ') is called');
    //clearTimeout(FadingTimeout);
    //StopFadingTimeout();

    if (UnFading)
    {
        DebugPrint('FadeUnneededIcons(' + ToKeep + ',' + lineid+ '): UnFading flag is set to on, quiting');
        return;
    }

    //alert('FadeUnneededIcons:\nToKeep:'+ToKeep+';\nlineid: '+lineid);
    //alert(FilteredCompanys);
    //First of all, we fading all companys
    for (i = 0; i < CompanysTable_byDate.length; i++) 
    {
        element = document.getElementById('company'+CompanysTable_byDate[i][0]);
        if (isset(element))
        {
            element.style.color="#AAAAAA";
        }
    }

    ToFadeDB = new Array();
    myerrmsg='';
    
    var current_element_debug;
    var tmp;

    for (i = 0; i < CurrentThumbnailSetSize; i++) 
    {
        //Due to Requirments changes changed logic from fading by type to fading by company id 
        //if (CurrentThumbnailSet[i][3]==ToKeep) {
        if (CurrentThumbnailSet[i][2]!=lineid) 
        {
            //fade this image ID
            if (CurrentThumbnailSet[i][3]!="is_blank")
            {
                ToFadeDB.push(CurrentThumbnailSet[i][0]);
            }
        } else {
            //ok then
            //Now we unfading highlited company
    
            //Bright highlighting overed company
            tmp = document.getElementById('company'+CurrentThumbnailSet[i][1]);
            if (isset(tmp)) 
            {
                tmp.style.color="black";
            } else 
            {
                //alert('BUG!!!!! Trying to hightlight at companies bar company that does not located there! trying to get element company'+CurrentThumbnailSet[i][1]);
            }; 
        }
    }
    //alert('ToFadeDB: ' + ToFadeDB.sort());
    //alert('NotToFadeDB: ' + ToLeaveDB.sort());

    for (j = 0; j <= 0.65; j = j + 0.05) 
    {
        for (i = 0; i < ToFadeDB.length; i++) 
        {
            current_element_debug = ToFadeDB[i];
            if (isset(current_element_debug))
            {
                CurrentTimeout = setTimeout("setOpacity(ToFadeDB["+i+"]," + (1-j) + ")", j * 400);
                FadingTimeout.push(CurrentTimeout);
            }
        }
    }

}

function StopFadingTimeout()
{
    DebugPrint('StopFadingTimeout() is called');
    //clearTimeout(FadingTimeout);
    //DebugPrint('UnFadeAllIcons(): FadingTimeout='+FadingTimeout)
    //alert('UnFadeAllIcons(): FadingTimeout='+FadingTimeout);
    for (i=0; i<FadingTimeout.length; i++)
    {
        CurrentTimeout = FadingTimeout[i];
        //DebugPrint('UnFadeAllIcons(): clearing timeout ' + CurrentTimeout)
        clearTimeout(CurrentTimeout);
    }
    FadingTimeout = new Array();
}

function UnFadeAllIcons() 
{
    UnFading=true;
    StopFadingTimeout();
    DebugPrint('UnFadeAllIcons() is called');

    //We need to unfade companys at companybar
    for (i = 0; i < CompanysTable_byDate.length; i++) 
    {
        element = document.getElementById('company'+CompanysTable_byDate[i][0]);
        if (isset(element)) 
        {
            element.style.color="#AAAAAA";
        }
    }

    // Now we'll unfade all thumbnails
    for (i = 0; i < CurrentThumbnailSetSize; i++) 
    {
            setOpacity(CurrentThumbnailSet[i][0], 1);
    }
    UnFading=false;
}

Array.prototype.shuffle = function( b )
{
 var i = this.length, j, t;
 while( i )
 {
  j = Math.floor( ( i-- ) * Math.random() );
  t = b && typeof this[i].shuffle!=='undefined' ? this[i].shuffle() : this[i];
  this[i] = this[j];
  this[j] = t;
 }

 return this;
}

function $(ID) 
{ 
    return document.getElementById(ID); 
}

// searches at array for LookFor, if found returns it's offset at array, otherwise returns -1
Array.prototype.in_array = function( LookFor )
{
 var i = 0;
 IsFound = false;
 while( !IsFound && i<=this.length)
 {
    if (this[i]==LookFor)
    {
        IsFound=true;
        break;
    }
    i++;
 }

 if (IsFound)
 {
    return i;
 } else {
    return -1;
 }
}


PicturesGallery = 
{
    // will hold description per category in same order like categories array (first=is_concept)
    Descriptions: ["is_concept description","is_identity description","is_packaging description","is_logotype description"],
    categories: ["is_concept","is_identity","is_packaging","is_logotype"],
    Pics_is_concept: [],
    Pics_is_identity: [],
    Pics_is_packaging: [],
    Pics_is_logotype: [],

    //CurrentDescription: "",
    CurrentCategory:"",
    CurrentPictures : [],
    LoadingPics : [],
    IsLoadingPic : 0,
    CurrentShownPicture : 0,
    IsAlreadyFixed : 0,
    IsRightShown : 0,
    AtLeastOnePic : 0, // indicates that there is at least one picture at catalog in order to avoid infinite loops
   
    GetStorage: function(category)
    {
       if (-1==this.categories.in_array(category))
       {
           alert('You should pass a right category to add to! Valid categories are: ' + this.categories);
           return false;
       }
   
       switch (category)
       {
           case "is_concept":
               PicsStorage = this.Pics_is_concept;
               this.CurrentCategory="is_concept";
               break;
           case "is_identity":
               PicsStorage = this.Pics_is_identity;
               this.CurrentCategory="is_identity";
               break;
           case "is_packaging":
               PicsStorage = this.Pics_is_packaging;
               this.CurrentCategory="is_packaging";
               break;
           case "is_logotype":
               PicsStorage = this.Pics_is_logotype;
               this.CurrentCategory="is_logotype";
               break;
   
           default:
               alert('invalid category passed!');
               return;
       }
   
       return PicsStorage;
    },
   
    AddToCategory : function(Link, category)
    {
        PicsStorage = this.GetStorage(category);
        if (!PicsStorage)
        {
            return;
        }
       
        PicsStorage.push(Link);
        this.AtLeastOnePic=1;
    },

    AddToCategoryFirst : function(Link, category) 
    { 
        PicsStorage = this.GetStorage(category);
        if (!PicsStorage)
        {
            return
        }
        PicsStorage.splice(0,0,Link); 
        this.AtLeastOnePic=1;
    },

    SetCategoryDescription: function (category, description)
    {
        CurrentCatOffset = this.categories.in_array(category);
        CurrentDescription = this.Descriptions[CurrentCatOffset];
        //alert('['+ category+']: before change: ' + CurrentDescription);

        this.Descriptions[CurrentCatOffset] = description;
        
        CurrentDescription = this.Descriptions[CurrentCatOffset];
        //alert('['+ category+']: after change: ' + CurrentDescription);
    },
   
    // Returns total number of pictures at all categories (all storages)
    GetTotalPictures: function ()
    {
        // getstorage have side effect of updating currentcategory so we need to preserve it
        OldCurrentCategory = this.CurrentCategory;

        TotalPictures = 0;
        for (i=0; i<this.categories.length;i++)
        {
            CurrentCategoryName = this.categories[i];
            CurrentCategory = this.GetStorage(CurrentCategoryName);
            TotalPictures = TotalPictures + CurrentCategory.length;
        }

        // restore CurrentCategory
        this.CurrentCategory=OldCurrentCategory;

        return TotalPictures;
    
    },

    ShowLeft : function() 
    { 
        // now we have ciclic logic, always show all, we don't need to show anything when 
        // we don't have pics at all or have only 1 pictrue


        // we show arrow only if we have more then 1 picture in total (there is where to go prev)
        TotalPictures = this.GetTotalPictures();
        if (TotalPictures>1)
        {
            //$("PicturesGalleryLeft").style.display = "inline"; 
            $("PicturesGalleryLeft").style.visibility = "visible";
        }

        /*if (this.CurrentPictures[this.CurrentShownPicture-1]) 
        {
            //$("PicturesGalleryLeft").style.display = "inline"; 
              $("PicturesGalleryLeft").style.visibility = "visible";
        } else if (this.CurrentPictures.length>1) {
            //this.ShowRight();
            this.ShowPrevCategory();
        } */
    },
    
    ShowRight : function() 
    { 
        // user already exited from our page (because of settimeout we still execute this code even we are already at another logic page) */
        if (!isset($("PicturesGalleryRight")))
        {
            return;
        }

        if ("false"==$("PicturesGalleryRight").complete)
        {
            setTimeout("self.parent.PicturesGallery.ShowRight()",100);
            return;
        }

        if (this.IsRightShown)
        {
            return;
        }

        // now we have ciclic logic, always show all
        TotalPictures = this.GetTotalPictures();
        if (TotalPictures>1)
        {
            $("PicturesGalleryRight").style.visibility = "visible";
            this.IsRightShown=1;
        }
        /*
        //alert($("PicturesGalleryRight").style.visibility);
        if (this.CurrentPictures[this.CurrentShownPicture+1]) 
        {
            //alert($("PicturesGalleryRight").style.display);
            //$("PicturesGalleryRight").style.display = "inline"; 
            $("PicturesGalleryRight").style.visibility = "visible";
            this.IsRightShown=1;
        } else {
            this.ShowNextCategory();
        } */
    },

    ShowPrevCategory: function ()
    {
        // validating that there is at least one picture at catalog, thus there is at least one category,
        // thus we cat go to prevcategory and we won't get to infinite recursion
        if (!this.AtLeastOnePic)
        {
            alert('Sorry, but currently pictures are not available this brand');
            return;
        }

        PrevCategory_index = this.categories.in_array(this.CurrentCategory);
        if (-1==PrevCategory_index)
        {
            return false;
        }

        PrevCategory_index--;
        if (PrevCategory_index<0)
        {
            PrevCategory_index=this.categories.length-1; // index is zero based, length isn't
        }

        PrevCategory = this.categories[PrevCategory_index];

        // skip categories without pictures
        if (this.GetStorage(PrevCategory).length==0)
        {
            this.ShowPrevCategory();
            return;
        }

        this.ShowCategory(PrevCategory, true);
    },

    ShowNextCategory: function ()
    {
        // validating that there is at least one picture at catalog, thus there is at least one category,
        // thus we cat go to next category in worst case we'll loop over all categories until we'll reach 
        // current category that have this 1 picture that probably current category thus we won't get to infinite recursion
        if (!this.AtLeastOnePic)
        {
            alert('Sorry, but currently pictures are not available for this line');
            return;
        }

        NextCategory_index = this.categories.in_array(this.CurrentCategory);
        if (-1==NextCategory_index)
        {
            return false;
        }

        NextCategory_index++;
        if (NextCategory_index>this.categories.length-1) // index is zero based, length isn't
        {
            NextCategory_index=0;
        }

        NextCategory = this.categories[NextCategory_index];

        // skip categories without pics
        if (this.GetStorage(NextCategory).length==0)
        {
            this.ShowNextCategory();
            return;
        }

        this.ShowCategory(NextCategory);
    },

    HideLeft : function() 
    { 
        //$("PicturesGalleryLeft").style.display = "none"; 
        $("PicturesGalleryLeft").style.visibility = "hidden"; 
    },

    DoLeft : function() 
    { 
        if (this.CurrentPictures[this.CurrentShownPicture-1]) 
        {
            this.Show(this.CurrentShownPicture-1); 
        } else {
            this.ShowPrevCategory();
        }
    },

    DoRight : function() 
    { 
        if(this.CurrentPictures[this.CurrentShownPicture+1]) 
        {
            this.Show(this.CurrentShownPicture+1); 
        } else {
            this.ShowNextCategory();
        }
    },
           
    HideRight : function() 
    { 
        if (!this.IsRightShown)
        {
            return;
        }
        //$("PicturesGalleryRight").style.display = "none"; 
        $("PicturesGalleryRight").style.visibility = "hidden"; 
        this.IsRightShown=0;
    },
    
    Reset: function() 
    {
        this.CurrentPictures = new Array();
        this.LoadingPics = new Array();
        this.Pics_is_concept = new Array();
        this.Pics_is_identity = new Array();
        this.Pics_is_packaging = new Array();
        this.Pics_is_logotype = new Array();
        this.Descriptions = new Array();
        this.IsLoadingPic = 0;
        this.CurrentShownPicture = 0;
        this.IsAlreadyFixed=0;
        this.IsRightShown=0;

        this.CurrentCategory = ""; 
        this.AtLeastOnePic = 0;
    },

    HighlightCategory: function(category)
    {
        if ($("cat_"+category))
        {
            $("cat_"+category).style.color='black';
        }
    },

    UnHighlightCategory: function(category)
    {
        if ($("cat_"+category))
        {
            $("cat_"+category).style.color='#717171';
        }
    },

    HighlightCategoryHandler: function(category)
    {
        // getstorage have side effect of updating currentcategory so we need to preserve it
        OldCurrentCategory = this.CurrentCategory;

        for (i=0; i<this.categories.length;i++)
        {
            CurrentCategory = this.categories[i];
            if (CurrentCategory==category)
            {
                this.HighlightCategory(CurrentCategory)
            } else {
                this.UnHighlightCategory(CurrentCategory)
            }
        }

        // restore CurrentCategory
        this.CurrentCategory=OldCurrentCategory;
    },

    ShowCategory: function(category, IsPrevCategory)
    {
        PicsStorage = this.GetStorage(category);
        if (!PicsStorage)
        {
            //this.CurrentPictures = new Array(); -> Do we want to leave old array to be shown to use instead of blank array ?!
            return;
        }

        this.CurrentPictures = PicsStorage;
        //this.GetStorage already did that ! this.CurrentCategory=category;

        // in case of previus category we should show LAST picture of category and not first because we scroll
        //   at line of pics back so we'll get to last picture of prev category and not to a first one
        if (isset(IsPrevCategory))
        {
            if (IsPrevCategory)
            {
                this.Show(this.CurrentPictures.length-1);
            }
        } else {
            this.Show(0);
        }

        // Hightlight new category and unhighlighting all others
        this.HighlightCategoryHandler(category);

        // Change category's description at UI
        CurrentCatOffset = this.categories.in_array(this.CurrentCategory);
        CurrentDescription = this.Descriptions[CurrentCatOffset];
        //alert(CurrentDescription);

        // at is_studio_mode (studio+case studies section) we don't have right panel with description
        if (isset(document.getElementById('line_description')) && isset(CurrentDescription) )
        {
            document.getElementById('line_description').innerHTML = CurrentDescription;
        }
    },

    Show : function(PictureToShow) 
    {
        //alert(this.CurrentPictures);
        if (navigator.userAgent.indexOf("MSIE")!=-1 && !this.IsAlreadyFixed)
        {
            //alert('fixing for IE');
            $("PicturesGalleryLeft").style.left="-5px";
            $("PicturesGalleryRight").style.left="4px";
            this.IsAlreadyFixed=1;
        }

        this.CurrentShownPicture = PictureToShow;
        this.LoadingPics[PictureToShow] = new Image();
        this.border="0";
        this.IsLoadingPic = 1;
        this.LoadingPics[PictureToShow].onload = function()
        {
            var MainPictureArea = $("MainPictureArea");
            if (!MainPictureArea)
            {
                this.IsLoadingPic  = 0;
                return;
            }

            //alert('Showing number: ' + PictureToShow);
            MainPictureArea.style.backgroundImage = "url('"+this.src+"')";
            //MainPictureArea.style.top  = (((354 - 20 - this.width) / 2) + 'px');
            MainPictureArea.style.left = (((940 - 20 - this.width) / 2) + 'px');
            MainPictureArea.style.width = this.width;
            MainPictureArea.style.height = this.height;
            $("MainPitureCenter").style.height = this.height;
            $("MainPitureRight").style.width = $("MainPitureLeft").style.width = Math.round((this.width) / 5)+"px";
            $("MainPitureCenter").style.width = (this.width - ((Math.round((this.width) / 5)) * 2)) - 10 + "px";
            $("MainPictureArea").style.width =  this.width + "px";
            $("MainPitureLeft").style.height = this.height;
            $("MainPitureRight").style.height = this.height;
            $("MainPicList").style.display = "";
            this.IsLoadingPic  = 0;
            //alert(this.style);
        }
        this.LoadingPics[PictureToShow].src = this.CurrentPictures[PictureToShow];
    }
}


function DebugPrint(value)
{
    return;
    debug = document.getElementById('debug_view'); 
    if (isset(debug))
    {
        debug.innerHTML = value + "<br>" + debug.innerHTML;
    }
}


