﻿ //-------------
// IMAGE BUTTON
//-------------

var ImageButton = new Class({
    initialize: function(imgElementCID, GraphicsPath, imgOn, imgOff, imgElementDisabledCID, isEnabled)
    {
        var imgElementDisabled;
        if (imgElementDisabledCID==null || imgElementDisabledCID=='' || imgElementDisabledCID=='undefined')
        {
            imgElementDisabled = null;            
        }
        else
        {
            imgElementDisabled = $(imgElementDisabledCID);
        }
        this.imageButtonClient = new ImageButtonClient($(imgElementCID), GraphicsPath, imgOn, imgOff, imgElementDisabled, isEnabled);
    },
    
    enable: function(imgElement, imgElementDisabled)
    {
        this.imageButtonClient.enable();    
    },
    
    disable: function(imgElement, imgElementDisabled)
    {   
        this.imageButtonClient.disable();    
    }
});

var ImageButtonClient = new Class({
   
    initialize: function(imgElement,GraphicsPath, imgOn, imgOff, imgElementDisabled, isEnabled)
    {
        this.imgElement = imgElement;
        this.imgElementDisabled = imgElementDisabled;
        imgElement.src = GraphicsPath + imgOff;
        imgElement.addEvent('mousedown', function(e){
	        e = new Event(e);
	        imgElement.src = GraphicsPath + imgOn;
	        e.stop();
        });
        imgElement.addEvent('mouseup', function(e){
	        e = new Event(e);
	        imgElement.src = GraphicsPath + imgOff;
	        e.stop();
        });
        imgElement.addEvent('mouseout', function(e){ //we need in case user do mousedown and move without mouseup
	        e = new Event(e);
	        imgElement.src = GraphicsPath + imgOff;
	        e.stop();
        });
      
        if (imgElementDisabled!=null)
        {
            if (isEnabled)
            {
                this.enable();
            }        
            else            
            {
                this.disable();
            }        
        }    
    },
    
    enable: function()
    {
        this.imgElement.style.display = '';
        this.imgElementDisabled.style.display = 'none';
    },
    
    disable: function()
    {
        this.imgElement.style.display = 'none';
        this.imgElementDisabled.style.display = '';
    }
});


var ImageButtonWithOver = new Class({
    initialize: function(imgElementCID, GraphicsPath, imgOn, imgOff, imgOver, clickFunctionName)
    {
        $(imgElementCID).src = GraphicsPath + imgOff;
    
        $(imgElementCID).addEvent('mousedown', function(e){
	        e = new Event(e);
	        $(imgElementCID).src = GraphicsPath + imgOn;
	        e.stop();
        });
        $(imgElementCID).addEvent('mouseup', function(e){
	        e = new Event(e);
	        $(imgElementCID).src = GraphicsPath + imgOff;
	        e.stop();
        });
        $(imgElementCID).addEvent('mouseover', function(e){
	        e = new Event(e);
	        $(imgElementCID).src = GraphicsPath + imgOver;
	        e.stop();
        });
        $(imgElementCID).addEvent('mouseout', function(e){
	        e = new Event(e);
	        $(imgElementCID).src = GraphicsPath + imgOff;
	        e.stop();
        });

        var x = clickFunctionName + "('" + imgElementCID + "');";
        eval(x);
    }
});


var SmartSlider = new Class({
    
    initialize: function(divSmartSliderID, divSlideID, cmdEditID, divCloseID, innerControlName, visible)
    {
        //we need class reference for the current class instance
        //we cannot use smartSlider1/2/3
        var classRef = this;
        
        this.innerControlName = innerControlName;
        this.innerControl = page[innerControlName];         
        this.divSmartSlider = $(divSmartSliderID);        
        this.divSlide = $(divSlideID);
        this.cmdEdit = $(cmdEditID);        
        this.divClose = $(divCloseID);                
        
        this.mySlider = new Fx.Slide(this.divSlide, {duration: 500, onComplete: this.onSlideComplete.bind(this), onStart: this.onSlideStart.bind(this) });
        
        if(!visible)
        {
            this.mySlider.hide();            
        }
        else //the section is visible
        {
            //hide edit button            
            this.cmdEdit.style.display = 'none';            
            //display "close"
            this.divClose.style.visibility = 'visible';  
                
            if(this.innerControlName == 'storyBoard')
            {            
                this.innerControl.show();
            }
        }

        this.cmdEdit.addEvent('click', function(e){
            e = new Event(e);            
            //display user control
            classRef.mySlider.slideIn();
            e.stop();
        });        

        this.divClose.addEvent('click', function(e){
            e = new Event(e);
            //hide user control
            classRef.mySlider.slideOut();                        
            e.stop();
        });
    },
    
    onSlideStart: function(){},
    
    fixEI6SlideBug: function(isOpen)
    {
        if (BrowserDetect.browser == "Explorer")
        {
            if(this.divSlide.parentElement)
            {
              if (isOpen) {
                this.divSlide.parentElement.setStyle('height', '0');
              }
              else {
                this.divSlide.parentElement.setStyle('height', 'auto');
              }
            }
        }
    },
    
    onSlideComplete: function()
    {   
        // When the slider open the div - he give the div height, 
        // We remove the height (height = '')
        // in order that the div will increase when we add scene or link        
        this.divSlide.parentNode.style.height = '';
        
        if ( !this.mySlider.open) //Slider is CLOSING
        {
            this.innerControl.hide();
               
            //display edit button            
            this.cmdEdit.style.display = '';
            //hide "close"            
            this.divClose.style.visibility = 'hidden';            
            this.fixEI6SlideBug(true);    
        }
        else //Slider is OPENING
        {           
            this.innerControl.show();
            
            //hide edit button
            this.cmdEdit.style.display = 'none';
            //display "close"
            this.divClose.style.visibility = 'visible';                       
            
            this.fixEI6SlideBug(false);    
        }                
    }    
});  

var PreLoader = new Class({

    initialize: function(divPreLoaderID, spanMsgID){
        this.divPreLoader = $(divPreLoaderID);
        this.spanMsg = $(spanMsgID);
    },
    
    show: function(message){
        this.spanMsg.innerHTML = message;
        this.divPreLoader.style.display = '';
    },

    hide: function(){
        this.divPreLoader.style.display = 'none';
    }
});

var SaveStatus = new Class({    
    
    initialize: function(){},
    
    setSaveStatus: function(classRef, status, btnActive, btnDisabled, preLoader, showMsg, divMsg)
    {
        classRef.isInSavingOperation = status;
        
        if (btnDisabled!=null)
        {
            if (status)
            {
                btnDisabled.style.display = '';
                btnActive.style.display = 'none';
            }
            else
            {
                btnDisabled.style.display = 'none';
                btnActive.style.display = '';
            }
        }
        else
        {
            btnActive.disabled = status;
        }
                    
        if (status)
        {
            if (divMsg!=null && divMsg!='undefined')
            {
                divMsg.style.display = 'none';
            }
            preLoader.show(showMsg);      
        }
        else
        {
            if (divMsg!=null && divMsg!='undefined')
            {
                divMsg.style.display = '';
            }    
            preLoader.hide();
        }
    }
});

var FieldLimit = new Class({
    
    initialize: function(textFieldID, limitNumber, type, fieldName, divLimitMsgID, startFromDifference)
    {
        var classRef = this, handleEvent;
        
        this.textField = $(textFieldID);
        this.limitNumber = parseInt(limitNumber,10);
        this.type = type;
        this.fieldName = fieldName;
        this.divLimitMsg = $(divLimitMsgID);
        this.startFromDifference = startFromDifference;
        
        this.handleEvent = function(e){                    
          classRef.showMessage(false);
        }        
        
        //bindWithEvent automatically passes mootools Event Class to the handleEvent function.
        this.textField.onkeyup = this.handleEvent.bindWithEvent(this.textField);
        this.textField.onfocus = this.handleEvent.bindWithEvent(this.textField);        
        this.textField.onpaste = this.handleEvent.bindWithEvent(this.textField);
        this.textField.oncut = this.handleEvent.bindWithEvent(this.textField);
    },
    
    showMessage: function(bool)
    {
        var msg;
        this.analyzeFieldText(bool);
        
        switch(this.type)
        {
            case '0':                
                msg = this.limitDifference + " characters left.";
                break;                                
            default:                                
                break;
        }
        this.divLimitMsg.innerHTML = msg;
        if (this.startFromDifference < this.limitDifference)
        {
            this.divLimitMsg.style.display='none';    
        }
        else
        {
            this.divLimitMsg.style.display='';    
        }
    },
    
    analyzeFieldText: function(bool)
    {
        this.limitDifference = this.limitNumber - this.textField.value.length;        
        if (this.limitDifference < 0)
        {
            this.limitDifference = 0;
        }
    }         
});

var ItemsDisplay = new Class({
    
    initialize: function(divContainerCID, itemsChangedCallback, hiddenSelectedCategories, userControlIndex, thumbSeedIndex, isMultipleInPage)
    {
        //Div element containing the displayed items
        this.divContainer = $(divContainerCID);
        //Callback function to call when the user removes an item
        this.itemsChangedCallback = itemsChangedCallback;
        //Array of displayed items.
        this.items = new Array();
        this.hiddenSelectedCategories = hiddenSelectedCategories;
        this.userControlIndex = userControlIndex;
        this.thumbSeedIndex = thumbSeedIndex;
        this.isMultipleInPage = isMultipleInPage;
        this.isDirty = false;
    },
    add: function(text, id)
    {
        //Avoid adding the "Select category" item
        if (id == -1)
            return;
        //Avoid adding the same item twice
        if (this.items.indexOf(id) != -1)
            return;
            
        var classRef = this;
        var divDisplayItem = document.createElement('div');
        
        //Create a DIV with the "Close" button, text and event.
        var divTextArea = new Element('div', 
            {
                'class': 'text_3 text_black displayItemBody'
            });        
        divTextArea.appendText(text);
        divTextArea.addEvent('click', function(e){
            e = new Event(e);	            
            classRef.remove(id, true);
            e.stop();
        });
        divTextArea.title = 'Click to remove.';
        
        //Create a hidden field with the item ID (we use him in remove function)
        var divHiddenID = new Element('div', {'class': 'displayItemHidden'});
        divHiddenID.appendText(id);
        
        //Append all 3 items into the container. make sure the hidden item is in index 1 (second item)
        //as the Remove function is counting on it.
        divDisplayItem.appendChild(divTextArea);
        divDisplayItem.appendChild(divHiddenID);
        
        this.divContainer.appendChild(divDisplayItem);

        //Add the new item to the items array
        this.items[this.items.length]=id;
        this.hiddenSelectedCategories.value = this.items.join()
        
        this.itemsChangedCallback(this.items, this.userControlIndex, this.thumbSeedIndex, this.isMultipleInPage);        
    },
    
    remove:function (id, shouldCallback)
    {
        for (i = 0; i< this.divContainer.childNodes.length; i++)
        {
            //look for ID in second element(divHiddenID).
            if (this.divContainer.childNodes[i].childNodes[1].innerHTML == id)
            {
                this.divContainer.removeChild(this.divContainer.childNodes[i]);
                this.items.erase(id);
                this.hiddenSelectedCategories.value = this.items.join();

                if(shouldCallback)
                    this.itemsChangedCallback(this.items, this.userControlIndex, this.thumbSeedIndex, this.isMultipleInPage);
                    
                this.isDirty = true;
            }
        }        
    }
});

var SelectCategories = new Class
({
    initialize: function(ddlCategoriesId, divSelectedCategoriesId, hiddenSelectedCategories, MAX_CATEGORIES, userControlIndex, thumbSeedIndex, isMultipleInPage)
    {
        var classRef = this;
        this.ddlCategories = $(ddlCategoriesId);
        this.divSelectedCategories = $(divSelectedCategoriesId);
        this.hiddenSelectedCategories = $(hiddenSelectedCategories);
        this.MAX_CATEGORIES = MAX_CATEGORIES;
        this.userControlIndex = userControlIndex;
        this.thumbSeedIndex = thumbSeedIndex;
        this.isMultipleInPage = isMultipleInPage;
        
        //Create the Selected categories display object
        this.itemsDisplay = new ItemsDisplay(this.divSelectedCategories, this.itemsChangedEventHandler, this.hiddenSelectedCategories, this.userControlIndex, this.thumbSeedIndex, this.isMultipleInPage);
        
        this.ddlCategories.addEvent('change', function(e){        
            e = new Event(e);
            classRef.changeDDlCategories();
            e.stop();
            window.focus();
	    });
    },
    
    changeDDlCategories : function()
    {
        this.itemsDisplay.add(
        this.ddlCategories[this.ddlCategories.selectedIndex].text,
        this.ddlCategories[this.ddlCategories.selectedIndex].value);
        this.itemsDisplay.isDirty = true;
    },
    
    //Call this function when the class is initialized to restore the control state after visiting
    // the server, or for initializing from server-side (by setting values to the hidden field)
    restoreState: function()
    {
        var existingItemsArray = this.hiddenSelectedCategories.value.split(',');
        
        for(var i=0; i < existingItemsArray.length ; i++)
        {
            this.addItem(existingItemsArray[i]);            
        }        
        
        this.limitCategoriesNumber();
    },
    
    //disable or enable ddlCategories
    limitCategoriesNumber: function()
    {
        if(this.MAX_CATEGORIES != -1) //if should limit categories number
        {
            if( this.itemsDisplay.items.length == this.MAX_CATEGORIES)
            {
                this.ddlCategories.disabled = true;
            }
            else
            {
                this.ddlCategories.disabled = false;
            }            
        }    
    },
    
    //This function is used by "restoreState" to add items to the control.
    //If you want to use it without the restore function just send null for index and array, and the categoryID in the item.
    addItem: function (item)
    {
        var ddl = this.ddlCategories;
        
        for(var i = 0; i < ddl.options.length; i++)
        {
            if (ddl.options[i].value == item)
            {
                this.itemsDisplay.add(
	                ddl.options[i].text,
	                ddl.options[i].value);
            }
        }
    },
    
    removeAllDdlItems : function(items)
    {
       //remove all categories except Top category
        for(var i = items.length-1 ; i >= 0 ;i--)
        {
            if(items[i] != 0)
            {
                this.itemsDisplay.remove(items[i], false);
            }
        }
    },

    //add and remove category call this function
     //if you use here the word "this" - it's of ItemsDisplay class because of it's CallBack function
    itemsChangedEventHandler: function(items, userControlIndex, thumbSeedIndex, isMultipleInPage)
    {
        var classRef = eval('selectCategoriesObj'+userControlIndex);

        if(items.length == 0)
        {
            classRef.ddlCategories.disabled = false;
        }
        
        if(items[items.length-1] == 0) //if last categry is Top category
        {

            //remove all categories except Top category
            classRef.removeAllDdlItems(items);

            //delete from CodeSeed all categories and Top category
            //send emptyItems for delete "playerSeed.categories = '0';" because it's default
            var emptyItems = new Array();
            classRef.generateCodeSeed(emptyItems, thumbSeedIndex);
                        
            classRef.ddlCategories.disabled = true;
            
        }
        else
        {
            if(isMultipleInPage) //if SelectCategories control is multiple in the page
            {

                //if you add third selectCategory control in the page - add <case "3":> to the switch.
                switch (userControlIndex)
                {                               
                    case "1": //this control inside PlayerSeed
                        generateCodePlayerSeedObj = eval('generateCodePlayerSeedObj'+thumbSeedIndex);
                        generateCodePlayerSeedObj.Categories = items.join();
                        generateCodePlayerSeedObj.generate();
                        break;                                                       
                    case "2": //this control inside ThumbSeed
                    
                        generateCodeThumbSeedObj = eval('generateCodeThumbSeedObj'+thumbSeedIndex);
                        generateCodeThumbSeedObj.Categories = items.join();
                        generateCodeThumbSeedObj.generate();                    
                        break;                
                }
                        
            }
            else
            {            
                classRef.generateCodeSeed(items, thumbSeedIndex);
            }        
        }        
     
        classRef.limitCategoriesNumber();
    },

    generateCodeSeed: function(items, thumbSeedIndex)
    {
            try //in some cases generateCodePlayerSeedObj is undefined and throw exception
            {
                generateCodePlayerSeedObj = eval('generateCodePlayerSeedObj'+thumbSeedIndex);
                generateCodePlayerSeedObj.Categories = items.join();
                generateCodePlayerSeedObj.generate();
            }
            catch(err){}
            
            try //in some cases generateCodeThumbSeedObj is undefined and throw exception (if SelectCategories work without GenerateCode)
            {                
                generateCodeThumbSeedObj = eval('generateCodeThumbSeedObj'+thumbSeedIndex);                                          
                generateCodeThumbSeedObj.Categories = items.join();
                generateCodeThumbSeedObj.generate();
                
                if (navigator.appName == "Microsoft Internet Explorer")
                    thumbSeed.draw();
            }
            catch(err){}
    }
 
});

var SelectTags = new Class
({
                
    initialize: function(txtTagsID, cmdAddID, divSelectedTagsID, hiddenSelectedTagsID, MAX_TAGS, TAG_MAX_LENGTH, tagsValidateID)
    {
        var classRef = this;
        this.txtTags = $(txtTagsID);
        this.cmdAdd = $(cmdAddID);        
        this.divSelectedTags = $(divSelectedTagsID);
        this.hiddenSelectedTags = $(hiddenSelectedTagsID);
        this.MAX_TAGS = MAX_TAGS;
        this.TAG_MAX_LENGTH = TAG_MAX_LENGTH;
        this.tagsValidate = $(tagsValidateID);
        this.tagsCounter = 0;
        
        //Create the Selected tags display object
        this.itemsDisplay = new ItemsDisplay(this.divSelectedTags, this.itemsChangedEventHandler, this.hiddenSelectedTags);       
	    
	    this.cmdAdd.addEvent('click', function(e){        
            e = new Event(e);

            classRef.tagsValidate.innerHTML = '';                                
            classRef.addTags();                
            
            classRef.itemsDisplay.isDirty = true;
            classRef.txtTags.value = '';            
            
            e.stop();
	    });	    	    
    },
    
    addTags: function()
    {
        var text = this.txtTags.value.trim();                
    
        //get array of tags from txtTags
        var arrTags = text.split(',');
        
        for(i=0; i < arrTags.length ;i++)
        {
            var tagText;
            
            if(arrTags[i].length > this.TAG_MAX_LENGTH) //cut the first 50 chars
            {
                tagText = arrTags[i].trim().substring(0,this.TAG_MAX_LENGTH);
            }
            else
            {
                tagText = arrTags[i].trim();
            }
            
            if( this.validateTag(tagText))
            {                       
                this.itemsDisplay.add(tagText, tagText);
                this.tagsCounter++;
            }
        }        
        
    },
    
    validateTag: function(tagText)
    {        
        if( this.itemsDisplay.items.length == this.MAX_TAGS)
        {
            this.tagsValidate.innerHTML = "Oops! Each video is limited to 10 tags. In order to add a new tag, please delete from the list";                                
            return false;
        }
        
        if( tagText == '')
        {
            this.tagsValidate.innerHTML = "Oops! You forgot to add a tag.";
            return false;
        }
        
        if(this.isTagExist(tagText))
        {
            this.tagsValidate.innerHTML = "Oops! You have already entered " + tagText;
            return false;
        }
        
        return true;
    },
    
    isTagExist: function(tagText)
    {
        // Check if tagTexxt incluse in items array
        var isExist = false;
        
        for (var i = 0; i < this.itemsDisplay.items.length; i++)
            {
                if (this.itemsDisplay.items[i].trim() == tagText)
                    {
                     isExist = true;
                     break;
                    }
            }
    
        return isExist;
    },
    
    //Call this function when the class is initialized to restore the control state after visiting
    // the server, or for initializing from server-side (by setting values to the hidden field)
    restoreState: function()
    {
        var arrTags = this.hiddenSelectedTags.value.split(',');        
        
        for(i=0; i < arrTags.length ;i++)
        {
            if(arrTags[i] != '')
            {
                this.itemsDisplay.add( arrTags[i], arrTags[i]);
                this.tagsCounter++;
            }
        }                        
    },
    
    //add and remove tag call this function
    //if you use here the word "this" - it's of ItemsDisplay class because of it's Call back function
    itemsChangedEventHandler: function(items)
    {
        //if user removed tag
        if(items.length +1 == page.selectTags.tagsCounter)
        {
            //update tagsCounter
            page.selectTags.tagsCounter--;
        }            
    }
});
