/*************************************************************************************

  ECubeInterfaceLibrary : a set of functions for creating dynamic interfaces
  
  It requires Utilities.js and EventHandlers.js
  
  
  functions:
  
  FUNCTION: ClearInputIfDefaultValue 
  ==================================
  
  clear the contents of input fields which have an attribute "valuedefault" if the input is
  clicked and the value is identical to valuedefault. 
  
  FUNCTION: OpenTabSheet
  ======================
  
  image elements that have an attribute istabfor attempt to open the corresponding tabsheet
  (an element with id tabsheet_something where something is the value of istabfor for the 
  corresponding tab). if the tab has a ChangeImageSourceMouseOver behavior, set its source
  to _on as well (and the source of other tabs to "nothing")
  to figure out which other sheets are in the same group, get all html elements that have
  the same parent as the current element. if there's a behavior  (see below)
  ChangeImageSourceMouseOver , mouse over images are taken care of as well
  
  
  ================================================================================
  =                                                                              =
  =                             BEHAVIOR FUNCTIONS                               =      
  =                                                                              =
  =  These attach to specific tags and act based on an attribute "behaviors".    =
  =  This attribute contains a white space separated list of possible            =
  =  behaviors.                                                                  =
  =                                                                              =
  =                                                                              =
  ================================================================================
  
  FUNCTION: Behavior_ChangeImageSourceMouseOver
  =============================================
  
  change the source of an image to which the ChangeImageSourceMouseOver behavior
  is attached, but only if the source image name doesn't end in _on
  
  FUNCTION: Behavior_ReplaceTeaserWithFullText
  ============================================
  
  replace a teaser text with a full text. The a that makes this
  happen has to be inside the element that contains the teaser text. We look upwards into the 
  DOM tree for the first element with an id teaser_something and then we look for an element
  fulltext_something. If both are found, hide teaser_something and show fulltext_something
  
*************************************************************************************/


// clear the contents of input fields which have an attribute "valuedefault" if the input is
// clicked and the value is identical to the valuedefault. 
function ClearInputIfDefaultValue(eventObject) {
    if(! this.getAttribute('valuedefault')) {
        return true;
    }
    var currentValue = this.value;
    if(! currentValue) {
        return true;
    };
    var defaultValue = this.getAttribute('valuedefault');
    if(! defaultValue) {
        return true;
    };
    if(currentValue == defaultValue) {
        this.value = '';
    };
    this.style.color = '#666666';
    return true;
}
tagListeners.addListenerForTag('input', 'onclick', ClearInputIfDefaultValue);


// image elements that have an attribute istabfor attempt to open the corresponding tabsheet (an
// element with id tabsheet_something where something is the value of istabfor for the 
// corresponding tab). if the tab has a ChangeImageSourceMouseOver behavior, set its source
// to _on as well (and the source of other tabs to "nothing")
// to figure out which other sheets are in the same group, get all html elements that have
// the same parent as the current element
function OpenTabSheet(eventObject) {
    if(! this.getAttribute('istabfor')) {
        return true;
    };
    var tabsheetWantedID = this.getAttribute('istabfor');
    tabsheetWantedID = 'tabsheet_' + tabsheetWantedID;
    var tabsheetWanted = document.getElementById(tabsheetWantedID);
    if(! tabsheetWanted) {
        return true;
    };
    // unfortunately we can't be sure how the display property of the
    // tabsheets are set. so set them to 'none' first
    var allTabs = this.parentNode.childNodes;
    for(var i = 0; i < allTabs.length ; i++) {
        var currentElement = allTabs[i];
        if(currentElement.tagName == 'IMG') {
            if(currentElement.getAttribute('istabfor')) {
                var tabsheet = document.getElementById('tabsheet_' + currentElement.getAttribute('istabfor'));
                tabsheet.style.display = 'none';
                // remove _on and _over from the source of the tab image
                // if necessary
                if(currentElement.getAttribute('behaviors')) {
                    if(currentElement.getAttribute('behaviors').match(/ChangeImageSourceMouseOver/)) {
                        var currentSource = currentElement.getAttribute('src');
                        if(currentSource.match(/_over\.[a-zA-Z]+$/)) {
                            currentSource = currentSource.replace(/_over\.([a-zA-Z]+)$/, '.$1');
                        };
                        if (currentSource.match(/_on\.[a-zA-Z]+$/)) {
                            currentSource = currentSource.replace(/_on\.([a-zA-Z]+)$/, '.$1');
                        };
                        currentElement.src=currentSource;
                    }
                }
            }
        };
    };
    // now open the requested tabsheet
    tabsheetWanted.style.display = 'block';
    // and set the source of the tab to _on if necessary
    if(this.getAttribute('behaviors')) {
        if(this.getAttribute('behaviors').match(/ChangeImageSourceMouseOver/)) {
            var imgSource = this.src;
            if(! imgSource) {
                return true;
            }
            if(imgSource.match(/_over\.[a-zA-Z]+$/)) {
                imgSource = newSource.replace(/_over\.([a-zA-Z]+)$/, '.$1');
            };
            if (! imgSource.match(/_on\.[a-zA-Z]+$/)) {
                    imgSource = imgSource.replace(/\.([a-zA-Z]+)$/, '_on.$1');
            };
            this.src=imgSource;
        }
    }
    return true;
     
}
tagListeners.addListenerForTag('img', 'onclick', OpenTabSheet);

// A objects with an attribute disableandalert set are disabled and the alert is shown
function disableAAndAlert(eventObject) {
  if(! this.getAttribute('disableandalert')) {
    return true;
  };
  var message = this.getAttribute('disableandalert');
  window.event? event.returnValue = false : eventObject.preventDefault(); /* IE : standards */
  alert(message);
  return false;
}
tagListeners.addListenerForTag('a', 'onclick', disableAAndAlert);

/*************************************************************************************

    Behavior functions

*************************************************************************************/




// change the source of an image to which the ChangeImageSourceMouseOver behavior
// is attached, but only if the source image name doesn't end in _on
function Behavior_ChangeImageSourceMouseOver(eventObject) {
    if(! this.getAttribute('behaviors')) {
        return true;
    };
        
    if(! this.getAttribute('behaviors').match(/ChangeImageSourceMouseOver/)) {
        return true;
    };
    var newSource = this.src;
    if(! newSource) {
        return true;
    }
    if(newSource.match(/_over\.[a-zA-Z]+$/)) {
        newSource = newSource.replace(/_over\.([a-zA-Z]+)$/, '.$1');
    } else {
        if (! newSource.match(/_on\.[a-zA-Z]+$/)) {
            newSource = newSource.replace(/\.([a-zA-Z]+)$/, '_over.$1');
        };
    };
    this.src=newSource;
    return true;
}
tagListeners.addListenerForTag('img', 'onmouseover', Behavior_ChangeImageSourceMouseOver);
tagListeners.addListenerForTag('img', 'onmouseout', Behavior_ChangeImageSourceMouseOver);

// ReplaceTeaserWithFullText: replace a teaser text with a full text. The a that makes this
// happen has to be inside the element that contains the teaser text. We look upwards into the 
// DOM tree for the first element with an id teaser_something and then we look for an element
// fulltext_something. If both are found, hide teaser_something and show fulltext_something
function Behavior_ReplaceTeaserWithFullText(eventObject) {
  if(! this.getAttribute('behaviors')) {
    return true;
  }
  if(! this.getAttribute('behaviors').match(/ReplaceTeaserWithFullText/)) {
    return true;
  };
  var safetycounter = 0;
  var currentParent = this.parentNode;
  var teaserObject = new Object;
  while(! teaserObject.id) {
    if(safetycounter > 15) {
      break;
    };
    if(currentParent.id && currentParent.id.match(/^teaser_/)) {
        teaserObject = currentParent;
      break;      
    } else {
      currentParent = currentParent.parentNode;
    }
    safetycounter++;
  };
  var fullTextID = teaserObject.id;
  fullTextID = fullTextID.replace(/^teaser_/, 'fulltext_');
  var fullTextObject = document.getElementById(fullTextID);
  if(! fullTextObject) {
    return true;
  };
  teaserObject.style.display = 'none';
  fullTextObject.style.display = 'block';
  

}
tagListeners.addListenerForTag('a', 'onclick', Behavior_ReplaceTeaserWithFullText);

// Show a popup. the url is in an attribute popup_url, the title in an attribute
// popup_title, the height in an attribute popup_height, the width in an attribute
// width and if you want scrollbars set an attribute popup_scrollbars to yes
//
// if you want the popup window to resize itself according to the size of a
// containing image, supply an attribute popup_autoimage = yes
function Behavior_ShowPopup(eventObject) {
  if(! this.getAttribute('behaviors')) {
    return true;
  }
  if(! this.getAttribute('behaviors').match(/ShowPopup/)) {
    return true;
  };
  var URL = this.getAttribute('popup_url');
  var Title = this.getAttribute('popup_title');
  var Height = this.getAttribute('popup_height');
  var Width = this.getAttribute('popup_width');
  var ScrollBars = this.getAttribute('popup_scrollbars');
  var WantResize = this.getAttribute('popup_autoimage');
  if(! URL) {
    return true;
  };
  window.event? event.returnValue = false : eventObject.preventDefault(); /* IE : standards */
  var parametersString = '';
  if(Height) {
    parametersString = parametersString + 'height=' + Height + ',';
  };
  if(Width) {
    parametersString = parametersString + 'width=' + Width + ',';
  }
  if(ScrollBars) {
    parametersString = parametersString + 'scrollbars=' + ScrollBars;
  } else {
    parametersString = parametersString + 'scrollbars=no';
  }
  
  
  // the title is more than likely invalid if we're opening a popup with an image only.
  // so open a window with an empty title instead
  var winTitle = Title;
  if(WantResize) {
    winTitle = '';
  }
  var winObj = window.open(URL, winTitle, parametersString);
  //window.open(URL, Title, parametersString);
  //window.open('http://www.kruidvatentertainmentshop.nl/ProductImages/3874932-m.jpg', 'test','height=100,width=100,scrollbars=no');

  if(WantResize) {
    var imageTitle = Title;
    var imageURL = URL;
    if(winObj) {
        with (winObj.document){
        writeln('<html><head><title>Loading...</title><style>body{margin:0px;}</style>');
        writeln('<sc'+'ript>');
        writeln('function reSizeToImage(){');
        writeln('window.resizeTo(100,100);');
        writeln('width=100-(document.body.clientWidth-document.images[0].width);');
        writeln('height=100-(document.body.clientHeight-document.images[0].height);');
        writeln('window.resizeTo(width,height);}');
        writeln('function doTitle(){document.title="'+imageTitle+'";}');
        writeln('</sc'+'ript>');
        writeln('</head><body bgcolor=FFFFFF scroll="no" onload="reSizeToImage();doTitle();self.focus()" onblur="self.close()">');
        writeln('<img name="George" src='+imageURL+' style="display:block"></body></html>');
        close();
      }
    }
  }
  
}

tagListeners.addListenerForTag('a', 'onclick', Behavior_ShowPopup);
//tagListeners.addListenerForTag('img', 'onclick', Behavior_ShowPopup);


