
/**
 * AWC Javascript Toolkit
 * Written for internal use at http://anywebcam.com
 *
 * Dependancies:
 * prototype - http://prototype.conio.net/
 */

var AWC = window.AWC || {};
AWC.namespace = function(ns) {

    if (!ns || !ns.length) {
        return null;
    }

    var levels = ns.split(".");
    var nsobj = AWC;

    // AWC is implied, so it is ignored if it is included
    for (var i=(levels[0] == "AWC") ? 1 : 0; i<levels.length; ++i) {
        nsobj[levels[i]] = nsobj[levels[i]] || {};
        nsobj = nsobj[levels[i]];
    }

    return nsobj;
};

AWC.namespace('generator');
AWC.namespace('module');
AWC.namespace('util');
AWC.namespace('widget');


/**
 * UTIL PACKAGE
 */

AWC.util.Cookie = function()
{
    var _navigatorCookieEnabled = (typeof navigator.cookieEnabled != "undefined" && navigator.cookieEnabled ? true : false);
    var _isEnabled = null;
    
    return {
        get: function(name, _default)
        {
            if(document.cookie.length > 0)
            {
                var nameEquals = name + "=";
                var ca = document.cookie.split(';');
                for(var i=0;i < ca.length;i++)
                {
                    var c = ca[i];
                    while (c.charAt(0)==' ') c = c.substring(1,c.length);
                    if (c.indexOf(nameEquals) == 0)
                        return c.substring(nameEquals.length,c.length);
                }
            }
            return _default || null;
        },
        
        set: function(name, value, days)
        {
            if(days) {
                var date = new Date();
                date.setTime(date.getTime()+(days*24*60*60*1000));
                var expires = "; expires="+date.toGMTString();
            }else {
                var expires = "";
            }
            document.cookie = name + "=" + value + expires + "; path=/";
        },

        remove: function(name)
        {
            AWC.util.Cookie.set(name, '', -1);
        },
        
        isEnabled: function() {
            if(AWC.util.Cookie._isEnabled ==  null)
            {
                if(AWC.util.Cookie._navigatorCookieEnabled) {
                    AWC.util.Cookie._isEnabled = AWC.util.Cookie._navigatorCookieEnabled
                } else {
                    if(typeof navigator.cookieEnabled == "undefined") {
                        document.cookie = "Cookie_isEnabledTest";
                        AWC.util.Cookie._isEnabled = document.cookie.indexOf("Cookie_isEnabledTest" != -1) ? true : false;
                    } else {
                        AWC.util.Cookie._isEnabled = false;
                    }
                } 
            }
            return AWC.util.Cookie._isEnabled;
        },
    
        toString: function() {
            return '[AWC.util.Cookie]';
        }
    }
}();

/*
 * Used to provide pagination from breadcrumbs so that a user can quickly
 * navigate back to the particular page of the board they were viewing 
 * before they decided to view the post.
 * 
 * Example URL conversion: /forums/7/general/ -> /forums/7/general/page-5/
 */
AWC.util.Crumbs = {
	appendPaging: function(page) {
		if(page == null) page = 'page';
		
		/* check for a page number in the cookies */
		var pageNum;
		if((pageNum = AWC.util.Cookie.get(page)) == null || pageNum <= 1) {
			return;
		}
		/* check for a valid dto url to paginate */
		var url;
		if(($('group-url') == null) ||  ((url = $F('group-url')) == null) || (url.length == 0)) {
			return;
		}
	
		/* append to existing breadcrumbs the page number markup */
		var crumbs;
		if(parent.frameMenu != null && (crumbs = parent.frameMenu.document.getElementById('crumbs')) != null) {
			crumbs.innerHTML += '&nbsp;<a href="' + url + 'page-' + pageNum + '/" target="frameContent">(' + pageNum + ')</a>';
		}
	},
	
	setPageCookie: function(page) {
		if(page == null) page = 'page';
		
		/* set group page number into a cookie */
		var pageNum;
		if(($('group-page') == null) ||  ((pageNum = $F('group-page')) == null) || (pageNum.length == 0)) {
			return;
		}
		/* Set cookie with group page num and set life to one day */
		AWC.util.Cookie.set(page, pageNum, 0.5);
	}
};


AWC.util.Delegate = {
    create: function( obj, func )
    {
        return function() { obj[func].apply( obj, arguments ); };
    },
    
    toString: function(){
            return '[AWC.util.Delegate]';
    }
};

/* options should contain: field, message */
AWC.util.Error = {
	
	display: function( options ) {
		alert(options.message);
	},	
    show: function( options ) {
        var field = $(options['field']);
        if(field) {
            field.innerHTML = '<p class="error">' + options['message'] + '</p>';
            Element.show(field);
        }
    },
    
    hide: function( options )
    {
        Element.hide(options['field']);
    },
    
    toString: function() {
        return '[AWC.util.Error]';
    }
};

AWC.util.Element = {
	insertAfter: function(parent, node, referenceNode) {
		parent.insertBefore(node, referenceNode.nextSibling);
	}
	
};

//TODO: AWC.util.Form
AWC.util.Form = {
    setSelectValue: function(element, value) {
        var options = $A(element.getElementsByTagName('option'));
        options.each( function( option ) {
            if(option.value == value) {
                option.selected = true;
                return;
            }
        });
    },
    
    getSelectValue: function(element) {
        var options = $A(element.getElementsByTagName('option'));
        for(var i = 0; i < options.length; i++) {
            if(options[i].selected == true) {
                return options[i].value;
            }
        }
        return null;
    },
    
    // value is optional, name can be used
    addOptionToSelect: function(element, name, value) {
    	var val = value || name;
    	element[element.options.length] = new Option(name, val);
    },
    
    // accepts an array, regardless of number of items to be selected
    setMultiSelectValue: function(element, values) {
        var options = $A(element.getElementsByTagName('option'));
        options.each( function( option ) {
            // check if value is in array, select if so
            var selected = false;
            for(var i = 0; i < values.length; i++) {
                if(option.value == values[i]) {
                    selected = true;
                }
            }
            option.selected = selected;
        });
    },
    
    // will return an array, regardless of number of items selected
    getMultiSelectValue: function(element) {
        var options = $A(element.getElementsByTagName('option'));
        
        var values = new Array();
        options.each( function( option ) {
            if(option.selected == true)
                values.push(option.value);
        });
        return values;
    },
    
    /* must use name, dealing with different id's for each radio */
    setRadioValue: function(element, value) {
        var radios = $A(document.getElementsByName(element));
        for(var i = 0; i < radios.length; i++) {
            if(radios[i].value == value)
                radios[i].checked = true;
        }
        return true;
    },
    
    /* must use name, dealing with different id's for each radio */
    getRadioValue: function(element) {
        var radios = $A(document.getElementsByName(element));
        for(var i = 0; i < radios.length; i++) {
            if(radios[i].checked)
                return radios[i].value;
        }
        return null;
    },
    
    setCheckboxValue: function(element, values) {
        var checkboxes = $A(document.getElementsByName(element));
        checkboxes.each( function(checkbox) {
            for(var i = 0; i < values.length; i++) {
                if(checkbox.value == values[i]) {
                    checkbox.checked = true;
                }
            }
        });
    },
    
    getCheckboxValue: function(element) {
        var checkboxes = $A(document.getElementsByName(element));
        var values = new Array();
        checkboxes.each( function(checkbox) {
            if(checkbox.checked)
                values.push(checkbox.value);
        });
        return values;
    },
    
    toString: function() {
        return '[AWC.util.Form]';
    }
};

AWC.util.Highlight = {


};


AWC.util.Number = {
	
	formatThousands: function(number) {
		number += '';
		x = number.split('.');
		x1 = x[0];
		x2 = x.length > 1 ? '.' + x[1] : '';
		var rgx = /(\d+)(\d{3})/;
		while (rgx.test(x1)) {
			x1 = x1.replace(rgx, '$1' + ',' + '$2');
		}
		return x1 + x2;
	}
	
	
};

// TODO: AWC.util.Pagination

// TODO: AWC.util.String = Class.create();
// TODO: trim, join, split

// TODO: get value from query string
AWC.util.URL = function()
{
	var _separator = '&amp;';
	var _equals = '=';

	return {
            encodeQueryString: function( $params, $separator, $equals ) {
                $separator = $separator || _separator;
                $equals = $equals || _equals;
                var $encoded = []; 
                for( var $prop in $params ) {
                        if( $params[ $prop ] != null && String($params[ $prop ]).length > 0 )
                        {
                                $encoded.push( $prop + $equals + $params[ $prop ] );
                        }
                }
                return $encoded.join( $separator );
            },
            
            decodeQueryString: function( $string, $separator, $equals ) {
                $separator = $separator || _separator;
                $equals = $equals || _equals;
                var decoded  = {};
                var groups = $string.split( $separator );
                for( var i=0,n=groups.length; i<n; i++ ) {
                        var param = groups[ i ].split( $equals );
                        // TODO: check params values actually exist.
                        $decoded[ params[0] ] = params[1];
                }
                return $decoded;
            },
            
            toString: function() {
                return '[AWC.util.URL]';
            }
	}
}();

// TODO: AWC.util.Validate

// TODO: popup, dimensions, blah
AWC.util.Window = {
    getClientWidth: function() {
        if(self.innerWidth)
            return self.innerWidth;
        else if(document.documentElement.clientWidth)
            return document.documentElement.clientWidth;
        else if(document.body.clientWidth)
            return document.body.clientWidth;
        else
            return null;
    },
    
    getClientHeight: function() {
        if(self.innerHeight)
            return self.innerHeight;
        else if(document.documentElement.clientHeight)
            return document.documentElement.clientHeight;
        else if(document.body.clientHeight)
            return document.body.clientHeight;
        else
            return null;
    },
    
    redirectAndClose: function(address, frame) {
        window.close();
        window.open(address, frame);
    },
    
    toString: function() {
            return '[AWC.util.Window]';
    }
};
