﻿
/* NAMESPACE Relational.Utility*/

Type.registerNamespace('Relational.Utility');

// toggle
//
Relational.Utility.toggle = function (target) {
    if (typeof(target) != 'object') { target = $get(target) } // Accept ID of element (string) or the element itself
    if (Relational.Utility.containsClassName(target, "Hidden") == true) 
        Relational.Utility.changeClassName(target, "Hidden", "Visible");
    else 
        Relational.Utility.changeClassName(target, "Visible", "Hidden");
}

// onDragGalleryItem 
//
// Adds RTB payload to a single element (typically fires on dragstart).
// The payload's inner HTML markup consists of the innerHTML of the passed payloadElement
//
Relational.Utility.onDragGalleryItem = function (evt, context) 
{
    var payloadElement = $get(context.payloadElementId);
	if (event != null)
	{
	    var payloadText = String.format("<photoGalleryPayload><DropHtml><![CDATA[{0}]]></DropHtml></photoGalleryPayload>", payloadElement.innerHTML);
		event.dataTransfer.setData("Text", payloadText);
		event.dataTransfer.effectAllowed = "copy"; 
	}
}    

// currentPageWithQueryString
//
// Analogue to Caudill.Utility.CurrentPageWithQuerySTring
// Returns name of current page with querystring
//
Relational.Utility.currentPageWithQueryString = function() {
    var urlParts = document.URL.split("/");
    var pageNameWithQueryString = urlParts[urlParts.length-1];
    return pageNameWithQueryString
}

// currentPage
//
// Analogue to Caudill.Utility.CurrentPage 
// Returns name of current page with no path or querystring (e.g. Articles.aspx)
//
Relational.Utility.currentPage = function() {
    var urlParts = document.URL.split("/");
    var pageNameWithQueryString = urlParts[urlParts.length-1];
    return pageNameWithQueryString.split("?")[0];
}

Relational.Utility.daysInFuture = function(days) {
    var date = new Date();   
	date.setTime(date.getTime()+(days*24*60*60*1000));
	return date;
}


// isPageValid
//
// This function checks the validation group of the input button and checks if the associated validators are valid.  If the button does not 
// belong to a validation group it validates the entire page.  
// NOTE: for the validationgroup support this function depends on js properties added by the Relational.LinkButton so if you call this with a 
// normal linkbutton with CausesValidation=false we will still validate the page (so change your asp:linkbutton to Relational:LinkButton)
//
Relational.Utility.isPageValid = function(button) {
    if (typeof(button.causesValidation) == 'undefined' || button.causesValidation == true) {
        // button causesValidation = true - check if page is valid
        if (typeof(Page_ClientValidate) == 'function') Page_ClientValidate(button.validationGroup);
        if (typeof(Page_IsValid) == 'undefined') { return true; } // e.g. no validators on page
        return Page_IsValid;
    }
    else {
        // button causesValidation = false 
        return true; 
    }
}


// addLoadEvent
//
// wires up load events from script modules before the pagemanager js object is valid
//
Relational.Utility.addLoadEvent = function(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	} else {
		window.onload = function() {
			oldonload();
			func();
		}
	}
}


// Rules
//
// based on Behaviour.js by Ben Nolan http://www.bennolan.com/behaviour
//
//Sample usage:
//
//        alertMessage = function (evt, context) 
//        {
//            var element = context.element;
//            var contactId = element.id.replace(new RegExp("ContactLink_Contact(\d*)"), "$1");
//            alert(context.payload + ": " + contactId);
//            return Relational.Utility.eventCancel(evt);
//        }
//           
//        var myrules = {
//	        'a._AlertHello' : function(element){
//                $addHandler(element, 'click', Function.createCallback(alertMessage, { element : element, payload : "Hello" }));
//	        }
//        };
//        	
//        Relational.Utility.Rules.register(myrules);
//        Relational.Utility.Rules.apply();
//
Relational.Utility.Rules = {

	list : new Array,
	
	register : function(sheet){
		Relational.Utility.Rules.list.push(sheet);
	},
	
	apply : function(){
		for (h=0;sheet=Relational.Utility.Rules.list[h];h++){
			for (selector in sheet){
				list = Relational.Utility.getElementsBySelector(selector);
				if (!list){continue;}
				for (i=0;element=list[i];i++){
					sheet[selector](element);
				}
			}
		}
	}

}


// getAllChildren is adapted from Simon Willison 2004 - used by getElementsBySelector
//
Relational.Utility.getAllChildren = function(e) {
  // Returns all children of element. Workaround required for IE5/Windows. Ugh.
  return e.all ? e.all : e.getElementsByTagName('*');
}


// getElementsBySelector 
//
// Gets all elements matching a CSS selector
// Adapted from Simon Willison http://simonwillison.net/2003/Mar/25/getElementsBySelector/
//
Relational.Utility.getElementsBySelector = function(selector) {
  // Attempt to fail gracefully in lesser browsers
  if (!document.getElementsByTagName) {
    return new Array();
  }
  // Split selector in to tokens
  var tokens = selector.split(' ');
  var currentContext = new Array(document);
  for (var i = 0; i < tokens.length; i++) {
    token = tokens[i].replace(/^\s+/,'').replace(/\s+$/,'');
    if (token.indexOf('#') > -1) {
      // Token is an ID selector
      var bits = token.split('#');
      var tagName = bits[0];
      var id = bits[1];
      var element = document.getElementById(id);
      if (tagName && element.nodeName.toLowerCase() != tagName) {
        // tag with that ID not found, return false
        return new Array();
      }
      // Set currentContext to contain just this element
      currentContext = new Array(element);
      continue; // Skip to next token
    }
    if (token.indexOf('.') > -1) {
      // Token contains a class selector
      var bits = token.split('.');
      var tagName = bits[0];
      var className = bits[1];
      if (!tagName) {
        tagName = '*';
      }
      // Get elements matching tag, filter them for class selector
      var found = new Array;
      var foundCount = 0;
      for (var h = 0; h < currentContext.length; h++) {
        var elements;
        if (tagName == '*') {
            elements = Relational.Utility.getAllChildren(currentContext[h]);
        } else {
            elements = currentContext[h].getElementsByTagName(tagName);
        }
        for (var j = 0; j < elements.length; j++) {
          found[foundCount++] = elements[j];
        }
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      for (var k = 0; k < found.length; k++) {
        if (found[k].className && found[k].className.match(new RegExp('\\b'+className+'\\b'))) {
          currentContext[currentContextIndex++] = found[k];
        }
      }
      continue; // Skip to next token
    }
    // Code to deal with attribute selectors
    if (token.match(/^(\w*)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/)) {
      var tagName = RegExp.$1;
      var attrName = RegExp.$2;
      var attrOperator = RegExp.$3;
      var attrValue = RegExp.$4;
      if (!tagName) {
        tagName = '*';
      }
      // Grab all of the tagName elements within current context
      var found = new Array;
      var foundCount = 0;
      for (var h = 0; h < currentContext.length; h++) {
        var elements;
        if (tagName == '*') {
            elements = Relational.Utility.getAllChildren(currentContext[h]);
        } else {
            elements = currentContext[h].getElementsByTagName(tagName);
        }
        for (var j = 0; j < elements.length; j++) {
          found[foundCount++] = elements[j];
        }
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      var checkFunction; // This function will be used to filter the elements
      switch (attrOperator) {
        case '=': // Equality
          checkFunction = function(e) { return (e.getAttribute(attrName) == attrValue); };
          break;
        case '~': // Match one of space seperated words 
          checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('\\b'+attrValue+'\\b'))); };
          break;
        case '|': // Match start with value followed by optional hyphen
          checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('^'+attrValue+'-?'))); };
          break;
        case '^': // Match starts with value
          checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) == 0); };
          break;
        case '$': // Match ends with value - fails with "Warning" in Opera 7
          checkFunction = function(e) { return (e.getAttribute(attrName).lastIndexOf(attrValue) == e.getAttribute(attrName).length - attrValue.length); };
          break;
        case '*': // Match ends with value
          checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) > -1); };
          break;
        default :
          // Just test for existence of attribute
          checkFunction = function(e) { return e.getAttribute(attrName); };
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      for (var k = 0; k < found.length; k++) {
        if (checkFunction(found[k])) {
          currentContext[currentContextIndex++] = found[k];
        }
      }
      // alert('Attribute Selector: '+tagName+' '+attrName+' '+attrOperator+' '+attrValue);
      continue; // Skip to next token
    }
    if (!currentContext[0]){
    	return;
    }
    // If we get here, token is JUST an element (not a class or ID selector)
    tagName = token;
    var found = new Array;
    var foundCount = 0;
    for (var h = 0; h < currentContext.length; h++) {
      var elements = currentContext[h].getElementsByTagName(tagName);
      for (var j = 0; j < elements.length; j++) {
        found[foundCount++] = elements[j];
      }
    }
    currentContext = found;
  }
  return currentContext;
}


// disableAnchor
//
// disables or enables a link (HtmlAnchor)
//
Relational.Utility.disableAnchor = function(
                        link, // name of or reference to the link
                        disable // true = disable, false = enable
                    ) 
{
    if (typeof(link) != 'object') { link = $get(link) } // Accept ID of element (string) or the element itself
    if(disable){
        var href = link.getAttribute("href");
        if(href && href != "" && href != null){
            link.setAttribute('href_bak', href);
        }
        link.removeAttribute('href');
        Relational.Utility.changeClassName(link,'Enabled','Disabled');
    }
    else{
        if (link.attributes['href_bak']) link.setAttribute('href', link.attributes['href_bak'].nodeValue);
        Relational.Utility.changeClassName(link,'Disabled','Enabled');
    }
}


Relational.Utility.setCookie = function(name, value, expires, path, domain, secure) 
{
  var curCookie = name + "=" + escape(value) +
      ((expires) ? "; expires=" + expires.toGMTString() : "") +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      ((secure) ? "; secure" : "");
  document.cookie = curCookie;
}

Relational.Utility.getCookie = function(name) 
{
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1) {
    begin = dc.indexOf(prefix);
    if (begin != 0) return null;
    } else
    begin += 2;
    var end = document.cookie.indexOf(";", begin);
    if (end == -1)
    end = dc.length;
    return unescape(dc.substring(begin + prefix.length, end));
}


// eventCancel
//
// Prevents event bubble up or any usage after this is called.
//
Relational.Utility.eventCancel = function (e)
{
   if (!e)
     if (window.event) e = window.event;
     else return;
   if (e.cancelBubble != null) e.cancelBubble = true;
   if (e.stopPropagation) e.stopPropagation();
   if (e.preventDefault) e.preventDefault();
   if (window.event) e.returnValue = false;
   if (e.cancel != null) e.cancel = true;
}  


// getElementsByClassName
//
// Returns an array of elements with the given tag name and class name
// Example: getElementsByClassName('div', 'foo') returns all elements of the form <div class="foo"> 
//
Relational.Utility.getElementsByClassName = function(targetTagName, targetClassName, rootElement) 
{
    if (!document.getElementsByTagName) return false; 
    if (typeof(rootElement) != 'object') { rootElement = document }
    var matchingElements = rootElement.getElementsByTagName(targetTagName);
    var results = new Array();
    var i = 0;
    // Go through all elements with the specified tag name 
    for (var j in matchingElements) {
        var matchingElement = matchingElements[j];
        if (typeof(matchingElement) != 'undefined' && matchingElement != null) {
            if (matchingElement.className) {
                // Go through all classnames for this element (class names can be separated by spaces, e.g. <div class="foo bar boo"> )
                var classNamesArray = matchingElement.className.split(" ");
                for (k in classNamesArray) {
                    if (classNamesArray[k] == targetClassName) {
                        // Got a match - add to results 
                        results[i++] = matchingElement;
                    } 
                }
            }
        }
    }
    return results;
}


// containsClassName
//
// Searches thru the classes and returns true if the element has the input classname in its list of cssclasses.
//
Relational.Utility.containsClassName = function (targetElement, className) 
{
    var classNamesArray = new Array();
    if (typeof(targetElement) != 'object') { targetElement = $get(targetElement) } // Accept ID of element (string) or the element itself
    if (!targetElement) return false; 
    if (targetElement.className) {
        // Go through all classnames for this element (class names can be separated by spaces, e.g. <div class="foo bar boo"> )
        classNamesArray = targetElement.className.split(" ");
        for (i in classNamesArray) {
            if (classNamesArray[i] == className) {
                return true;
            } 
        }
    }
    return false;
}    

// changeClassNameHandler
//
// provides an event handler for changeClassName below (unpacks variables, cancels event, etc)
//
Relational.Utility.changeClassNameHandler = function (evt, context) 
{
    var sourceElementId = context.sourceElementId;
    var targetElementId = sourceElementId.replace(new RegExp(context.triggerIdPattern), context.targetIdPattern);
    Relational.Utility.changeClassName(targetElementId, context.targetClassNameBefore, context.targetClassNameAfter); 
    if (context.appendCancel == true) return Relational.Utility.eventCancel(evt);
}

// changeClassName
//
// Replaces the "before" class with the "after" class in the target element.
// If the "before" class isn't one of the target element's classes, the "after" class is appended to the class list.
//
// Example: changeClassName(foo, "HighlightOff", "HighlightOn") 
// Changes <div class="BigDiv HighlightOff Green"> to <div class="BigDiv HighlightOn Green">
// Changes <div class="BigDiv"> to <div class="BigDiv HighlightOn">
//
//Relational.Utility.changeClassName = function (evt, context) 
Relational.Utility.changeClassName = function (targetElement, classNameBefore, classNameAfter) 
{
    var classNamesArray = new Array();
    if (typeof(targetElement) != 'object') { targetElement = $get(targetElement) } // Accept ID of element (string) or the element itself
    if (!targetElement) return false;   
    if (targetElement.className) {
        // Go through all classnames for this element (class names can be separated by spaces, e.g. <div class="foo bar boo"> )
        classNamesArray = targetElement.className.split(" ");
        for (i in classNamesArray) {
            if (classNamesArray[i] == classNameBefore || classNamesArray[i] == classNameAfter) {
                // Found either the "before" or "after" class, remove it
                classNamesArray[i] = "";
            } 
        }
    }
    classNamesArray.push(classNameAfter); // add back the "after" class 
    // Put everything back into a single string 
    targetElement.className = classNamesArray.join(" ");
}    


// clickInside
//
// Finds a link in the trigger div with the named class, and navigates to its href location
// Use as the onclick handler function for a div
Relational.Utility.clickInside = function(triggerElement, targetLinkClassName) 
{
    if (typeof(triggerElement) != 'object') { triggerElement = $get(triggerElement) } // Accept ID of element (string) or the element itself
    var links = triggerElement.getElementsByTagName('a'); 
    // Find a with class=targetLinkClassName
    for (var i=0; i<links.length; i++) {
        if (Relational.Utility.containsClassName(links[i], targetLinkClassName)) {
            // Act as if the link itself had been clicked
            // Note: If the URL is external (different site), IE7 will load it in a new browser window
            if(links[i].target == "_blank") {
                if(links[i].className.indexOf('Popup')>-1) {
                    window.open(links[i].href, String.format('childwin_{0}', links[i].id), 'height=600,width=400,location=no,menubar=no,status=no,toolbar=no,scrollbars=yes');
                }
                else {
                    window.open(links[i].href, String.format('childwin_{0}', links[i].id));
                }
            }
            else {
                window.location = links[i].href;
            }
        } 
    }  
}



if(typeof(Sys)!=='undefined')Sys.Application.notifyScriptLoaded();