var AMLI = {};

function _get(id){
    return document.getElementById(id);
}

function _get_style_value(el, prop){
	var val = el.style[prop] || false;
	if (!val) {
		if (document.defaultView) 
		    val = document.defaultView.getComputedStyle(el,null).getPropertyValue(prop);
		else if (el.currentStyle) 
		    val = el.currentStyle[prop];
	}	    
    return val;
}

function _amli_make_function(obj, func) {
    var refThis = obj;
    return function() {
        return func.apply(refThis, Array.prototype.slice.call(arguments, 2));
    }
}

function _amli_add_event(o, ev, f, c){
    
    if(c==undefined)c=false;
    if(o.attachEvent){
        o.attachEvent('on' + ev, f);
    }else if(o.addEventListener){
        o.addEventListener(ev, f, c);
    }
}

function _amli_get_event_element(e){
    
	if (!e) var e = window.event;
	
	if (e.target) t = e.target;
	else if (e.srcElement) t = e.srcElement;
	
	if (t.nodeType == 3) t = t.parentNode;
	
    return t;    
}

function _amli_get_elements(obj,names) {

	var elements = new Array();
	for (var i=0;i<names.length;i++) {
		var tags = obj.getElementsByTagName(names[i]);
		for (var j=0;j<tags.length;j++) {
			elements.push(tags[j]);
		}
	}
	var testNode = elements[0];
	if (!testNode) return [];
	if (testNode.sourceIndex) {
		elements.sort(function (a,b) {
				return a.sourceIndex - b.sourceIndex;
		});
	}
	else if (testNode.compareDocumentPosition) {
		elements.sort(function (a,b) {
				return 3 - (a.compareDocumentPosition(b) & 6);
		});
	}
	return elements;
}

//function _amli_getkey(e){
//	if (!e) var e = window.event
//	if (e.keyCode) code = e.keyCode;
//	else if (e.which) code = e.which;
//	return code;
//}

function openCenterWindow(URL,width,height,style) {

    var w=660, h=590, bw, bh, bl, bt, topPos, leftPos;

    if (width > 0 ){w=width;}

    if (height > 0){h=height;}

    if (document.all){
        bw = screen.width;
        bh = screen.height;
        bw = window_info.getWidth(); //document.body.clientWidth;
        bh = window_info.getHeight(); //document.body.clientHeight;
        bl = window.screenLeft;
        bt = window.screenTop;
    }else if (document.layers){
        bw = window.outerWidth;
        bh = window.outerHeight;
        bl = window.screenX;
        bt = window.screenY;
    }

    leftPos = Math.floor((bw-w)/2) + bl;
    topPos = Math.floor((bh-h)/2) + bt;
    window.open(URL, '', style + ',width=' + w + ',height=' + h + ',top=' + topPos + ',left=' + leftPos);
}

var element_info = function(el) {

    var t = el.offsetTop;
    var l = el.offsetLeft;
    var b = el.offsetHeight;
    var r = el.offsetWidth;

    if (el.style && el.style.position == 'absolute') {
        t = el.style.top;
        l = el.style.left;
    } else {
        while (el.offsetParent != null) {
            el = el.offsetParent;
            t += el.offsetTop;
            l += el.offsetLeft;
        }
    }

    return { top: t, left: l, bottom: t + b, right: l + r };
};

var window_info = AMLI.Window = function(){
    return {
         getAll :       function(){
                            return [this.getHeight(),this.getWidth(),this.getScrollY(),this.getScrollX()];
                        }
        ,getHeight :    function(){
                            return this.filter(
                                window.innerHeight ? window.innerHeight : 0,
                                document.documentElement ? document.documentElement.clientHeight : 0,
                                document.body ? document.body.clientHeight : 0
                            );
                        }    
        ,getWidth :     function(){
                            return this.filter(
		                        window.innerWidth ? window.innerWidth : 0,
		                        document.documentElement ? document.documentElement.clientWidth : 0,
		                        document.body ? document.body.clientWidth : 0
                            );
                        }
        ,getScrollY :   function(){
                            return this.filter(
		                        window.pageYOffset ? window.pageYOffset : 0,
		                        document.documentElement ? document.documentElement.scrollTop : 0,
		                        document.body ? document.body.scrollTop : 0
                            );
                        }     
        ,getScrollX :   function(){
                            return this.filter(
		                        window.pageXOffset ? window.pageXOffset : 0,
		                        document.documentElement ? document.documentElement.scrollLeft : 0,
		                        document.body ? document.body.scrollLeft : 0
                            );
                        }                                     
        ,filter :       function(n_win, n_docel, n_body) {
                            var n_result = n_win ? n_win : 0;
                            if (n_docel && (!n_result || (n_result > n_docel)))
                                n_result = n_docel;
                            return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
                         }
        };  
}();

//special effects javascript
//TODO: create separate amli_effects.js ??

/*
    Extending Math object with some Motion Tweens
    See http://www.robertpenner.com/easing/penner_chapter7_tweening.pdf around p14 to understand what they are doing.
    (c) 2003 Robert Penner (http://www.robertpenner.com/easing/), Open Source BSD License.
*/
Math.linearTween = function (t, b, c, d) {
    return c*t/d + b;
};
Math.easeInOutSine = function (t, b, c, d) {
    return c/2 * (1 - Math.cos(Math.PI*t/d)) + b;
};
Math.easeInOutExpo = function (t, b, c, d) {
    if ((t/=d/2) < 1)
        return c/2 * Math.pow(2, 10 * (t - 1)) + b;
    return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
};

/*
    AMLI.Effects 
    Custom AMLI Transition and Animations helpers.
*/
AMLI.Effects = {};
AMLI.Effects.Transition = function(def){

    if(!def.duration) def.duration = 500;
    if(!def.fps) def.fps = 50;
    if(!def.uom) def.uom = 'px';
    if(!def.tween) def.tween = Math.easeInOutSine;
    
    def.run = function (valuefrom,valueto,when,onstart,onfinish){
            
        if(!when) when = 0;
    	if (this.timer) return;
    	
    	this.valuefrom = valuefrom;
    	this.valueto = valueto;
    	this.onfinish = onfinish;
    	
    	this.timestart = new Date().getTime();
    	this.timer = setInterval(this.bindstep(), Math.round(1000/this.fps)+when);
    };
    
    def.step = function(){
               
		var timenow = new Date().getTime();
		var valuenow = null;
		
		if (timenow < this.timestart + this.duration){
			var timelapsed = timenow - this.timestart;
			valuenow = this.tween(timelapsed, this.valuefrom, this.valueto - this.valuefrom, this.duration);
		} else {
			clearInterval(this.timer);
			this.timer = null;
			valuenow = this.valueto;
		}

		var style = this.element.style;
		
		if(this.type=='opacity')
		{
    		if (valuenow == 0){
    			if(style.visibility != 'hidden') style.visibility = 'hidden';
    		} else {
    			if(style.visibility != 'visible') style.visibility = 'visible';
    		}
    		
    		if (window.ActiveXObject)
    		    style.filter = 'alpha(opacity=' + valuenow*100 + ')';
    		    
    		style.opacity = valuenow;   
    		
		}else{
		    
		    style[this.type] = valuenow + this.uom;
		    
		}
		
		if(this.timer==null && this.onfinish){
		    this.onfinish();
		    this.onfinish = null;   
		}
		
    };
    
	def.bindstep = function(){
		var rEf = this;
		return function(){
			return rEf.step();
		};
	};       
	
    return def;
};

AMLI.Effects.Animation = function(def){
    
    def.transitions = new Array();
    
    for(var i=0;i<def.length;i++){
        
        def.transitions[i] = new AMLI.Effects.Transition(def[i]);
        
    }
    
    def.run = function(){
        for(var i=0;i<this.transitions.length;i++){
            
            this.transitions[i].run.apply(this.transitions[i],arguments[i]);
            
        }        
    };
    
    return def;
};

AMLI.Effects.CollapsibleDiv = function() {

    return {

        init: function(divid) {

            this.div = _get(divid);
            this.collapsed = false;

            if (this.div) {

                this.originalHeight = this.div.clientHeight;

                if (!this.animation) {

                    this.animation = new AMLI.Effects.Animation(
                            [{ element: this.div, type: 'height' }
                            , { element: this.div, type: 'opacity' }]
                        );
                }
            } else {
                alert('Developer Error: Element "' + divid + '" is not on the page.');
            }
        },
        toggle: function() {

            if (this.collapsed) {
                this.expand();
            } else {
                this.collapse();
            }
        },
        collapse: function() {

            this.animation.run([this.originalHeight, 0], [1, 0]);
            this.collapsed = true;
        },
        expand: function() {

            this.animation.run([this.div.clientHeight, this.originalHeight], [0, 1]);
            this.collapsed = false;
        }
    };
};

var _amli_browser = AMLI.Browser = function() {
    return {
        // Checks for version of IE.
        Version: function() {
            var v = 999;
            if (navigator.appVersion.indexOf("MSIE") != -1) {
                v = parseFloat(navigator.appVersion.split("MSIE")[1]);
            }
            return v;
        }
    };
}();

AMLI.GetBrowserInfo = function() {
                
    window.onerror = null;
    var info = '<table cellpadding="0" cellspacing="0" width="100%">';
    info += '<tr><td>navigator.userAgent:  </td><td>' + navigator.userAgent + '</td></tr>';
    info += '<tr><td>navigator.appName:     </td><td>' + navigator.appName + '</td></tr>';
    info += '<tr><td>navigator.appVersion:  </td><td>' + navigator.appVersion + '</td></tr>';
    info += '<tr><td>navigator.appCodeName: </td><td>' + navigator.appCodeName + '</td></tr>';
    info += '<tr><td>navigator.platform:    </td><td>' + navigator.platform + '</td></tr>';
    info += '<tr><td>navigator.javaEnabled: </td><td>' + navigator.javaEnabled() + '</td></tr>';
    info += '<tr><td>screen.colorDepth:     </td><td>' + window.screen.colorDepth + '</td></tr>';
    info += '<tr><td>screen.fontSmoothing:  </td><td>' + window.screen.fontSmoothingEnabled + '</td></tr>';
    info += '<tr><td>screen.width:          </td><td>' + window.screen.width + '</td></tr>';
    info += '<tr><td>screen.height:         </td><td>' + window.screen.height + '</td></tr>';
    info += '<tr><td>screen.availWidth:     </td><td>' + window.screen.availWidth + '</td></tr>';
    info += '<tr><td>screen.availHeight:    </td><td>' + window.screen.availHeight + '</td></tr>';
    
    var w,h;
    
    if( typeof( window.innerWidth ) == 'number' ) {
        //Non-IE
        w = window.innerWidth;
        h = window.innerHeight;
    } else if( document.documentElement 
                && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
        //IE 6+ in 'standards compliant mode'
        w = document.documentElement.clientWidth;
        h = document.documentElement.clientHeight;
    } else if( document.body 
                && ( document.body.clientWidth || document.body.clientHeight ) ) {
        //IE 4 compatible
        w = document.body.clientWidth;
        h = document.body.clientHeight;
    }
    
    info += '<tr><td>window Actual Width:    </td><td>' + w + '</td></tr>';
    info += '<tr><td>window Actual Height:   </td><td>' + h + '</td></tr>';
    
    var numPlugins = navigator.plugins.length;
    info += '<tr><td>Plugin count: </td><td>' + numPlugins + '</td></tr>';
    
    for (var i = 0; i < numPlugins; i++) {
        plugin = navigator.plugins[i];
        info += '<tr><td style="padding-top:4px;">plugin.name:</td><td>' + plugin.name + '</td></tr>';
        info += '<tr><td>plugin.filename:      </td><td>' + plugin.filename + '</td></tr>';
        info += '<tr><td>plugin.description:   </td><td>' + plugin.description + '</td></tr>';            
    }
    
    info += '</table>';
    
    return info;
}

/*
    Used in AMLIFavortiesSmall,CMSRegionCommunities2,AMLIFeaturedDevelopments
*/
function toggle_community_preview(id) {

    var comm = _get("com_" + id);
    var prev = _get("prv_" + id);
    var tr = _get("tr_" + id);

    var collapsed = comm.className == "PreviewCollapsed";

    if (!prev.animation)
        prev.animation = new AMLI.Effects.Animation(
                [{ element: prev, type: 'height', duration: 350 }
                , { element: prev, type: 'opacity', duration: 350}]);

    if (collapsed) {

        comm.className = "PreviewExpanded";
        if (tr != null) {
            tr.className = "PreviewExpanded";
        }
        prev.animation.run([0, 380], [0, 1]);
    } else {

        prev.animation.run([380, 0], [1, 0]);
        comm.className = "PreviewCollapsed";
        if (tr != null) {
            tr.className = "PreviewCollapsed";
        }
    }
}

/*
    Used in AMLILogin
*/
AMLI.Login = function(div_id,email_id,pword_id,button_id){
    this.div_id = div_id;
    this.email_id = email_id;
    this.pword_id = pword_id;
    this.button_id = button_id;   
    _amli_add_event(window,'load',_amli_make_function(this,this.init)); 
}
AMLI.Login.prototype.init = function(){
    this.div = _get(this.div_id);
    this.email = _get(this.email_id);
    this.pword = _get(this.pword_id);
    this.button = _get(this.button_id);
    _amli_add_event(this.email, 'keydown', AMLI.Login.enterKey );
    _amli_add_event(this.pword, 'keydown', AMLI.Login.enterKey );
}
AMLI.Login.prototype.show = function(link) {

    var pos = new element_info(link);
    
    this.div.style.display = 'block';
    this.div.style.top = pos.top + 'px';
    this.div.style.left = (pos.right-this.div.offsetWidth) + 'px';
    
    if (this.email.value == '')
        this.email.focus();
    else
        this.pword.focus();

    window.scrollTo(0, 0);
}
AMLI.Login.prototype.hide = function() {
    this.div.style.display = 'none';
    this.pword.value = '';
}
AMLI.Login.enterKey = function(e) {

    if (e.keyCode == 13 || e.which == 13){
        e.returnValue = false;
        e.cancel = true;
        _amli_login.button.click();
    }
}

/*
    AMLI.IE6TransparentPNGFix
    Workaround that allows IE 5.5 and 6 to render transparency in PNGs.  The concept was borrowed,
    but modified, from "supersleight" (http://24ways.org/2007/supersleight-transparent-png-in-ie6).
*/
var _ie6pngfix = AMLI.IE6TransparentPNGFix = function() {
	
    var fixneeded = document.all &&
                        (navigator.appVersion.indexOf('MSIE 6')!=-1 
                         || navigator.appVersion.indexOf('MSIE 5')!=-1);
    var rtn;
    
    if(fixneeded){
	    rtn =
	    {
	        pngreg : /\.png/i
	        ,shim : '/images/spacer.gif'
		    ,fixAll : function(el){
		        var root = el ? el : document.getElementById('aspnetForm');
		        var list = _amli_get_elements(root,['IMG','DIV']);
        		for (var i = list.length - 1, obj = null; obj = list[i]; i--) {
        			this.fixObj(obj);
        		}
        		this.fixObj(root);
        	}
        	,fixObj : function(obj){
    	        var mode = 'scale';
    	        var src = null;
    	        if (obj.tagName=='IMG'){
    				if(obj.src.match(this.pngreg)){
    				    src = obj.src;
    				    if(obj.style.filter.indexOf(src)>-1)return;
    				    //window.status += '|'+obj.width+':'+obj.height;
                		obj.style.width = obj.offsetWidth + "px";
                		obj.style.height = obj.offsetHeight + "px";
                		obj.src = this.shim;        				    
    				}
    			}else if (obj.currentStyle && obj.currentStyle.backgroundImage.match(this.pngreg)) {
    			    var bg	= obj.currentStyle.backgroundImage;
    			    src = bg.substring(5,bg.length-2);
    			    if(obj.style.filter.indexOf(src)>-1)return;
            		if (obj.currentStyle.backgroundRepeat == 'no-repeat') {
            			mode = 'crop';
            		}
            		obj.style.backgroundImage = 'url('+this.shim+')';
    			}
    			
    			if(src)
    			    obj.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "', sizingMethod='" + mode + "')";    		
        	}
        };        
        
        _amli_add_event(window,'load',_amli_make_function(rtn,rtn.fixAll));
        
    }else{
        rtn = {fixAll:function(el){}};
    }

    return rtn;
}();