/* Simple Accordion Script 
 * Requires Prototype and Script.aculo.us Libraries
 * By: Brian Crescimanno <brian.crescimanno@gmail.com>
 * http://briancrescimanno.com
 * This work is licensed under the Creative Commons Attribution-Share Alike 3.0
 * http://creativecommons.org/licenses/by-sa/3.0/us/
 */

if (typeof Effect == 'undefined')
  throw("You must have the script.aculo.us library to use this accordion");

var Accordion = Class.create({

    initialize: function(id, defaultExpandedCount) {
        if(!$(id)) throw("Attempted to initalize accordion with id: "+ id + " which was not found.");
        this.accordion = $(id);
        this.options = {
            toggleClass: "accordion-toggle",
            toggleActive: "accordion-toggle-active",
            contentClass: "accordion-content"
        }
        this.contents = this.accordion.select('div.'+this.options.contentClass);
        this.isAnimating = false;
        this.maxWidth = 0;
        this.current = defaultExpandedCount ? this.contents[defaultExpandedCount] : this.contents[0];
        this.toExpand = null;

        this.checkMaxWidth();
        this.initialHide();
        this.attachInitialMaxWidth();

        var clickHandler =  this.clickHandler.bindAsEventListener(this);
        this.accordion.observe('click', clickHandler);
    },

    expand: function(el) {
        this.toExpand = el.previous('div.'+this.options.contentClass);
	if (this.toExpand && (this.current != this.toExpand)) {
            if (this.toExpand.id == 'home-content') {
		document.getElementById('left_bar').style.backgroundImage = 'url(/sites/all/themes/highpointcreative/css/left-home.jpg)';
	    } else {
                document.getElementById('left_bar').style.backgroundImage = 'url(/sites/all/themes/highpointcreative/css/left.jpg)';
	    }
	    this.toExpand.show();
            this.animate();
	    fetch_data(this.toExpand);
        }
    },

    checkMaxWidth: function() {
        for(var i=0; i<this.contents.length; i++) {
            if(this.contents[i].getWidth() > this.maxWidth) {
                this.maxWidth = this.contents[i].getWidth();
            }
        }
    },

    attachInitialMaxWidth: function() {
		this.current.previous('div.'+this.options.toggleClass).addClassName(this.options.toggleActive);
        if(this.current.getWidth() != this.maxWidth) this.current.setStyle({width: this.maxWidth+"px"});
    },

    clickHandler: function(e) {
        var el = e.element();
        if(el.hasClassName(this.options.toggleClass) && !this.isAnimating) {
            this.expand(el);
        }
    },

    initialHide: function(){
        for(var i=0; i<this.contents.length; i++){
            // if(this.contents[i] != this.current) {
	    if (!this.contents[i].hasAttribute("data-current")) {
                this.contents[i].hide();
                this.contents[i].setStyle({width: 0});
            } else {
		this.current = this.contents[i];
	    }
        }
    },

    animate: function() {
        var effects = new Array();
        var options = {
            sync: true,
            scaleFrom: 0,
            scaleContent: false,
            transition: Effect.Transitions.sinoidal,
            scaleMode: {
		originalHeight: this.accordion.getHeight(),
                originalWidth: this.maxWidth
                // originalHeight: this.maxHeight,
                // originalWidth: this.accordion.getWidth()
            },
            scaleX: true,
            scaleY: false
        };

        effects.push(new Effect.Scale(this.toExpand, 100, options));

        options = {
            sync: true,
            scaleContent: false,
            transition: Effect.Transitions.sinoidal,
            scaleX: true,
            scaleY: false
        };

        effects.push(new Effect.Scale(this.current, 0, options));

        var myDuration = 0.75;

	options = {
            sync: true,
            from: 0,
	    to: 1
        };

	effects.push(new Effect.Opacity(this.toExpand, options));

	options = {
            sync: true,
            from: 1,
	    to: 0
        };

	effects.push(new Effect.Opacity(this.current, options));

        new Effect.Parallel(effects, {
            duration: myDuration,
            fps: 35,
            queue: {
                position: 'end',
                scope: 'accordion'
            },
            beforeStart: function() {
                this.isAnimating = true;
                this.current.previous('div.'+this.options.toggleClass).removeClassName(this.options.toggleActive);
                this.toExpand.previous('div.'+this.options.toggleClass).addClassName(this.options.toggleActive);
            }.bind(this),
            afterFinish: function() {
                this.current.hide();
                this.toExpand.setStyle({ width: this.maxWidth+"px" });
                this.current = this.toExpand;
                this.isAnimating = false;
            }.bind(this)
        });
    }

});


var Accordion2 = Class.create({

    initialize: function(id, defaultExpandedCount) {
        if(!$(id)) throw("Attempted to initalize accordion with id: "+ id + " which was not found.");
        this.accordion = $(id);
        this.options = {
            toggleClass: "accordion-toggle",
            toggleActive: "accordion-toggle-active",
            contentClass: "accordion-content"
        }
        this.contents = this.accordion.select('div.'+this.options.contentClass);
        this.isAnimating = false;
        this.maxWidth = 0;
        this.current = defaultExpandedCount ? this.contents[defaultExpandedCount] : this.contents[0];
        this.toExpand = null;

        this.checkMaxWidth();
        this.initialHide();
        this.attachInitialMaxWidth();

        var clickHandler =  this.clickHandler.bindAsEventListener(this);
        this.accordion.observe('click', clickHandler);
    },

    expand: function(el) {
        this.toExpand = el.previous('div.'+this.options.contentClass);
	if (this.toExpand && (this.current != this.toExpand)) {
            this.current.style.display = 'none';
	    this.current.style.width = "0px";
	    this.toExpand.style.display = 'inherit';
	    this.toExpand.style.width = "574px";
	    this.current = this.toExpand;
	    fetch_data(this.toExpand);
	    if (this.toExpand.id == 'home-content') {
		document.getElementById('left_bar').style.backgroundImage = 'url(/sites/all/themes/highpointcreative/css/left-home.jpg)';
	    } else {
                document.getElementById('left_bar').style.backgroundImage = 'url(/sites/all/themes/highpointcreative/css/left.jpg)';
	    }
        }
    },

    checkMaxWidth: function() {
        for(var i=0; i<this.contents.length; i++) {
            if(this.contents[i].getWidth() > this.maxWidth) {
                this.maxWidth = this.contents[i].getWidth();
            }
        }
    },

    attachInitialMaxWidth: function() {
		this.current.previous('div.'+this.options.toggleClass).addClassName(this.options.toggleActive);
        if(this.current.getWidth() != this.maxWidth) this.current.setStyle({width: this.maxWidth+"px"});
    },

    clickHandler: function(e) {
        var el = e.element();
        if(el.hasClassName(this.options.toggleClass) && !this.isAnimating) {
            this.expand(el);
        }
    },

    initialHide: function(){
        for(var i=0; i<this.contents.length; i++){
            // if(this.contents[i] != this.current) {
	    if (!this.contents[i].hasAttribute("data-current")) {
                this.contents[i].hide();
                this.contents[i].setStyle({width: 0});
            } else {
		this.current = this.contents[i];
	    }
        }
    },

    animate: function() {}

});

document.observe("dom:loaded", function() {
    BrowserDetect.init();
    if ((BrowserDetect.browser == 'Firefox') &&
	(BrowserDetect.version < 3.6))
	accordion = new Accordion2("test-accordion");
    else
	accordion = new Accordion("test-accordion");
})

function make_xmlhttprequest() {
    if (window.XMLHttpRequest) {
	// If IE7, Mozilla, Safari, etc: Use native object
	return new XMLHttpRequest()
    } else {
	if (window.ActiveXObject){
	    // ...otherwise, use the ActiveX control for IE5.x and IE6
	    return new ActiveXObject("Microsoft.XMLHTTP");
	}
    }
}

function fetch_data(div) {
  var xmlhttp = make_xmlhttprequest();
  if (xmlhttp.overrideMimeType)
      xmlhttp.overrideMimeType("text/xml");
  xmlhttp.open("GET",div.getAttribute('data-href'),true);
  xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState == 4) {
      // set_page_data(div,xmlhttp.responseXML);
	div.innerHTML = xmlhttp.responseText;
    }
  }
  xmlhttp.send(null);
  perform_track("/" + div.getAttribute('data-href'));
}

function perform_track(path) {
    var tracker = document.getElementById("test-accordion").tracker;
    tracker._trackPageview(path);
}

function fetch_node_data(div, node) {
  var xmlhttp = make_xmlhttprequest();
  if (xmlhttp.overrideMimeType)
      xmlhttp.overrideMimeType("text/xml");
  xmlhttp.open("GET",'/subpage.php?node=' + node,true);
  xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState == 4) {
      // set_page_data(div,xmlhttp.responseXML);
	div.innerHTML = xmlhttp.responseText;
    }
  }
  xmlhttp.send(null);
}

function set_page_data(div, page_dom) {
  var to_populate = div.firstChild;
  while (to_populate.hasChildNodes()) {
    to_populate.removeChild(to_populate.firstChild);
  }

  var body = page_dom.getElementsByTagName('body')[0];

  if (body) {
      for (var i = 0; i < body.childNodes.length; i++) {
	  XMLtoHTML(to_populate,body.childNodes[i]);
      }
  }
}

function XMLtoHTML(html_parent, xml_node) {
    if (xml_node.nodeType == 3) {
	html_parent.appendChild(document.createTextNode(xml_node.data));
    } else {
	var html_node = document.createElement(xml_node.nodeName);
	if (xml_node.hasAttributes()) {
	    for (var i = 0; i < xml_node.attributes.length; i++) {
                var attribute = xml_node.attributes[i];
		html_node.setAttribute(attribute.name,attribute.value);
	    }
	}
        if (xml_node.hasChildNodes()) {
	    for (var i = 0; i < xml_node.childNodes.length; i++) {
		XMLtoHTML(html_node,xml_node.childNodes[i]);
	    }
	}
	html_parent.appendChild(html_node);
    }

}

function click_tab(tab) {
    var event = document.createEvent('MouseEvents');
    event.initMouseEvent('click',true, true, window, 1, 0, 0, 0, 0,
                         false, false, false, false, 0, null);
    document.getElementById(tab.getAttribute('page')).dispatchEvent(event);
}

function swap_content(tab, node) {
    var content_area = document.getElementById(tab.getAttribute('page') + '-content');
    fetch_node_data(content_area,node);
}

function toggle_on(element) {
    var links = document.getElementsByTagName('a');
    for (var i = 0; i < links.length; i++) {
	if (element === links[i]) {
            var div = document.getElementById(element.getAttribute('data-list'));
	    fetch_node_data(div,div.getAttribute('data-node'));
	    div.style.display = 'inherit';
	} else if (links[i].hasAttribute('data-list')) {
	    document.getElementById(links[i].getAttribute('data-list')).style.display = 'none';
	}
    }
}

function show_card(node_id) {
    document.getElementById('directions-text').style.display = 'none';
    var card_div = document.getElementById('card');
    fetch_node_data(card_div,node_id);
    card_div.style.display = 'inherit';
    card_div.className = 'card';
}

function show_map(node_id) {
    var card_div = document.getElementById('card');
    fetch_node_data(card_div,node_id);
    card_div.style.display = 'inherit';
    card_div.className = 'map';
}

function display_portfolio(img) {
    fetch_node_data(document.getElementById('blurb'),
                    img.getAttribute('data-node'));
}
