/* Copyright 2009 Xsevo */
var xs = {
    onload:[],
    main: function(opts) {
        if (opts) {
            if (opts.k) {
                try {
                    var target = xsInitBank[opts.k];
                    if (!target) throw 1;
                } catch(e) { }
                if (target) { try { target(); } catch (e) { xsJSError(e); } }
            }
            if (opts.p) {
                this.path = opts.p;
                this.save = this.path +'save/';
            }
        }
        this.load();
    },
    register: function(fn,env) {
        this.onload.push(fn.bind(env || this));
    },
    load: function() {
        if (this.onload) {
            this.onload.each(function (fn) {
                try { fn.apply(this); } catch (e) { xsJSError(e); }    
            }.bind(this));
        }       
    }
};

function xsJSError(err) { alert(err.message); }
function isUndefined(a) { return typeof a == 'undefined'; }

var xsUtil = {
    getQs: function(key, def) {
        if (!def) def = '';
        var qs_str = document.location.href;
        var offset = qs_str.indexOf('?');
        var qs = qs_str.substring(offset+1)
        qs = $H(qs.toQueryParams());
        if (qs[key]) return qs[key];
        return def;
    },
    getQsInt: function(idx, def) {
        if (!idx) idx = 0;
        if (!def) def = '';
        var qs_str = document.location.href;
        var offset = qs_str.indexOf('?');
        if (offset <= 0) {
            var uri = qs_str.substring(8);
        } else {
            var uri = qs_str.substring(8,offset-1)   
        }
        var ints = uri.split('/');
        var c = 0;
        for (var i=0;i<ints.length;i++) {
            try {
                var v = parseInt(ints[i]);
                if (isNaN(v)) throw 1;
                if (c == idx) return v;
                c++;
            } catch(e) {}
        }
        return def;
    },
    go: function(u,f) {
        try { if (!f) { document.location.href=u;} else { window.open(u); } } catch(e) { xsJSError(e); }
    },
    goChild: function(el) {
        try {
            var els = el.getElementsByTagName('a'); 
            if (els && els[0] && els[0].href) this.go(els[0].href);
        } catch(e) { xsJSError(e); }
    },
    getEventId: function(el, ev) {
        try {
            if (ev) {
                var full_id = ev.currentTarget.id
                var pair = full_id.split('_');
                if (pair[1]) return pair[1];
            }
            throw 1;
        } catch(e) {
            var max = 8, i = 0, node = el;
            while (i < max) {
                i++;
                try {
                    var full_id = node.id;
                    var pair = full_id.split('_');
                    if (pair[1]) return pair[1];                
                } catch(e) { }
                try {
                    node = node.parentNode;
                    if (!node) { throw 1; }
                } catch (e) { return null; }
            }
            return null;
        }   
    },
    hideImage: function(el, ev) {
        Element.hide(el);
        Event.stop(ev);
    },
    getParentBg: function(el) {
        var node = el.parentNode;
        try {
            while (node) {
                var pbg = null;
                try {
                    pbg = Element.getStyle(node, 'background-color');
                } catch(e) {}
                if (pbg && pbg != 'transparent') { return pbg; }
                node = node.parentNode;
            }
        } catch (e) { }
        return '#fff';
    },
    getBg: function(el) {
        var node = el;
        try {
            while (true) {
                var pbg = Element.getStyle(node, 'background-color');
                if (pbg && pbg != 'transparent') { return pbg; }
                node = node.parentNode;
            }
        } catch (e) { xsJSError(e); }
        return '#fff';
    },
    setChildStyle: function(el, style) {
        $A($(el).childNodes).each( function(c) { Element.setStyle(c, style); } );
    },
    getWindowSize: function() {
        if (!isUndefined(window.innerHeight)) {
            return {height:window.innerHeight, width:window.innerWidth};
        } else {
            return {height:document.documentElement.clientHeight, width:document.documentElement.clientWidth};
        }
    },
    getDocHeight: function() {
        try {
            if(window.innerHeight && window.scrollMaxY ) {
                return window.innerHeight + window.scrollMaxY;
            } else if (document.body.scrollHeight>document.body.offsetHeight ) {
                return document.body.scrollHeight;
            } else {
                return document.body.offsetHeight+document.body.offsetTop;
            }
        } catch(e) { return 0; }
    },
    getSelection: function () {
        try {
            if (window.getSelection) {
                return window.getSelection();
            } else if (document.getSelection) {
                return document.getSelection();
            } else if (document.selection) {
                return document.selection.createRange().text;
            }
        } catch (e) { xsJSError(e); }
        return null;
    },
    clear: function(el) {
        Field.clear(el);
        return false;
    },
    isIE: function() {
        return document.all && !window.opera;   
    },
    isIE6: function() {
        return document.all && !window.opera && (!window.XMLHttpRequest); 
    },
    isIE7: function() {
        return document.all && !window.opera && window.XMLHttpRequest;   
    },
    includeJS: function(f,c) {
        var js = document.createElement('script');
        if (c) {
            js.onload = c;
            js.onreadystatechange = function () { if (/(complete|loaded)/.test(js.readyState)) c(); }
        }
        js.setAttribute('type', 'text/javascript');
        js.setAttribute('src', script_path+f);
        document.getElementsByTagName('head')[0].appendChild(js);
        //Safari doesn't support script onload
        if (c && /WebKit|KHTML/i.test(navigator.userAgent)) setTimeout(c, 1000);
    },
    focusError: function(errs, form) {
        if (!form) {
            try {
                form = document.forms[0];
            } catch (e) { return; }
        }
        var els = $A(form.elements);
        var err = errs.split(',');
        for (var i=0;i<els.length;i++) {
            var el = els[i];
            if (err.indexOf(el.name) >= 0) {
                try {
                    if (el.type == 'text') {
                        Field.activate(el);
                    } else {
                        Field.focus(el);
                    }
                    new Effect.Highlight(el, {delay:1});
                    return;
                } catch (e) { }
            }
        }
    },
    numSort: function(a, b) {
        return a - b;
    },
    getHostPath: function() {
        var p = document.location.href;
        var hs = p.indexOf('//')+2;
        var hl = p.substr(hs).indexOf('/');
        return p.substr(0,hs+hl);
    }
};


var xsHoverBase =  {
    BgId:'hbg',BgClass:'hbg',Boxes:0,Visible:false,
    _init: function() {
        if (this.Box) return true;
        this.Box = $(this.BoxId);
        if (this.Box) return true;
        try {
            this.Box = document.createElement("div");
            if (this.ClassName) Element.addClassName(this.Box, this.ClassName);
            this.Box.id = this.BoxId;
            document.getElementsByTagName('body')[0].appendChild(this.Box);
            if (this.Draggable) {
                    var d_opts = {};
                    if (xsUtil.isIE()) d_opts = {starteffect:false, endeffect:false};
                    try {
                        new Draggable(this.Box, d_opts);
                    } catch(e) {                        
                        xsUtil.includeJS('dragdrop.js', function() { try { new Draggable(this.Box, d_opts); } catch(e) { } }.bind(this));
                    }
            }
            if (this.ShowBg) {
                this.Bg = $(this.BgId);
                if (!this.Bg) {
                    try {
                        this.Bg = document.createElement('div');
                        if (this.BgClass) Element.addClassName(this.Bg, this.BgClass);
                        this.Bg.id  = this.BgId;
                        document.getElementsByTagName('body')[0].appendChild(this.Bg);
                        Event.observe(this.Bg, 'click', this.hide.bind(this), false);
                    } catch(e) { xsJSError(e); }    
                }
                
            }
            if (!this.NoAutoHide) {
                Event.observe(this.Box, 'mouseout', this.boxHide.bind(this), false);
                Event.observe(this.Box, 'mouseover', this.boxClear.bind(this), false);
            }
            this.Fade = !xsUtil.isIE();
        } catch (e) { xsJSError(e); return false; }
        return false;
    },
    boxClear: function(ev) {
        if (this.BoxTimer) {
            try {
                clearInterval(this.BoxTimer);
            } catch(e) { xsJSError(e); }
            this.BoxTimer = null;
        }
    },
    boxHide: function(ev) {
        var tg = (window.event) ? ev.srcElement : ev.target;
        if (tg.nodeName != 'DIV') { Event.stop(ev); return; }
        var reltg = (ev.relatedTarget) ? ev.relatedTarget : ev.toElement;
        while (reltg != tg && reltg.nodeName != 'BODY') {
            reltg = reltg.parentNode;
            if (reltg == tg) { Event.stop(ev); return; }
        }
        if (this.Box) {
            try {
                this.boxClear();
                this.BoxTimer = setTimeout(this._boxHide.bind(this), 500);
            } catch(e) { xsJSError(e); }
        }
        Event.stop(ev);
    },
    _boxHide: function() {
        if (this.Box) {
            try {
                Element.hide(this.Box);
                this.Visible = false;
                if (this.Bg) {
                    xsHoverBase.Boxes--; if (xsHoverBase.Boxes < 0) xsHoverBase.Boxes = 0;
                    if (!xsHoverBase.Boxes) Element.hide(this.Bg);
                }
            } catch(e) { xsJSError(e); }
        }
    },
    hide: function() {
        this.Action = null;
        this.boxClear();
        this._boxHide();
        return false;
    },
    prepBox: function() {
        Element.setStyle(this.Box, {display: 'block', visibility:'hidden', top:0, left:0});
        if (this.Fade) Element.setOpacity(this.Box, 0.0);
        if (this.Bg) {
            xsHoverBase.Boxes++;
            var h = xsUtil.getDocHeight();
            //IE7 won't set opacity on elements taller than ~2000px
            if (h < 2000 || !xsUtil.isIE7()) Element.setStyle(this.Bg, {display:'block', height:h+'px'});
        }
    },
    showBox: function(l,t) {
        var s = {visibility: 'visible'}
        if (l) s.left = l+'px';
        if (t) s.top = t+'px';
        Element.setStyle(this.Box, s);
//        Element.setStyle(this.Box, {visibility: 'visible', left:l+'px', top:t+'px'});
        if (this.Fade) new Effect.Opacity(this.Box, {duration:0.3, from:0.0, to:1}); 
        this.Visible = true;
    }
};

var xsMsg = {
    BoxId:'msg-box',ClassName:'hb msg-box',ShowBg:true,
    BoxHeader:'<div><div class="t"></div><div class="c"><div class="o"><div class="m cf">',
    BoxFooter: '</div></div></div><div class="b"></div></div>',
    alert: function(m,act) {
        if (act) this.Action = act;
        this._init();
        this.Box.innerHTML = this.BoxHeader + m + '<br /><br /><ul class="btn"><li><a href="#" onclick="return xsMsg.action()">Ok</a></li></ul>' + this.BoxFooter;
        this.show();
    },
    confirm: function(m,act) {
        if (act) this.Action = act;
        this._init();
        this.Box.innerHTML = this.BoxHeader + m + '<br /><br /><ul class="btn"><li><a href="#" onclick="return xsMsg.action()">Ok</a></li><li><a href="#" onclick="return xsMsg.hide()">Cancel</a></li></ul>' + this.BoxFooter;
	this.show();
    },
    menu: function(m,l) {
        this._init();
        var buf = '';
        l.each(function (a) { buf += '<li><a href="#" onclick="return '+a[1]+';">'+a[0]+'</a></li>'; });
        this.Box.innerHTML = this.BoxHeader + m + '<br /><br /><ul class="btn">'+buf+'</ul>' + this.BoxFooter;
	this.show();
    },
    action: function() {
        try {
            if (this.Action) this.Action();
        } catch(e) { xsJSError(e); }
        this.hide();
        return false;
    },
    show: function() {
        try {
            this.prepBox();
            var size = Element.getDimensions(this.Box)
            var wsize = xsUtil.getWindowSize();
            var hover_left = Math.round((wsize.width - size.width) / 2);
            var hover_top = Math.round((wsize.height - size.height) / 2) + (document.documentElement.scrollTop || document.body.scrollTop);
            this.showBox(hover_left,hover_top);
        } catch (e) { xsJSError(e); }
    }
};
Object.extend(xsMsg, xsHoverBase);

var xsValidate =  {
	test: function(f) {
		try {
			f.each(function(f) {
            	if (this.valid(f[0], f[2])) return;
            	xsMsg.alert(f[1], function(x) { try { Field.select(x); } catch(e) {}; Field.focus(x); new Effect.Highlight(x, {delay:0.25}); }.bind(this,$(f[0])));
            	throw 1;
        	}.bind(this));
		} catch (e) { return false; }
		return true;
	},
    valid: function(el,o) {
        try {
            var o = o || {};
    		var e = $(el);
    		if (o.ifp && !e) return true;
            var v = e ? (o.cb ? e.checked : e.value.strip()) : '';
            if (o.opt && !v) return true;
            if (v == "" || v == null) return false;
            if ((o.num || o.nz) && !/^[\d\,\.]+$/.test(v)) return false;
            if (o.nz && !parseInt(v)) return false;
            if (o.re && !o.re.test(v)) return false;
            return true;
        } catch(e) {}
        return false;
    }
};

var xsArticle = {
    VideoData:{target:'vbox'},
	go: function(id, by, only, filter, page) {
		if (!page) page = 1;
		var params = {Sort:by, Only:only, Filter:filter};
		new Ajax.Updater({success:'cat_'+id}, xs.path+'c/'+id+'/0/page/'+page+'/bg/', { parameters: params });
		return false;
	},
	setupVideos: function(opts) {
        Object.extend(this.VideoData, opts||{});
    },
	queueVideos: function(opts) {
	    xs.register(this.drawVideos.bind(this, opts), this);
	},
	drawVideos: function(opts) {
	    if (!opts.videos) return;
	    var vd = this.VideoData;
	    opts.videos.each(function(v) {
	        var target = vd.target+'-'+v.Id;
	        var target_embed = target+'-embed';
	        t = target;
	               
	        var base_path = xsUtil.getHostPath()+xs.path+'id/'+opts.Id+'/'+v.URLTitle+'/';
	        
    	    var flashvars = {
    	        file: this.fixURL(v.URL),
    	        width: vd.width,
    	        height: vd.height,
    	        skin: vd.skin?vd.path+vd.skin:'',
    	        image: opts.pv?this.fixURL(opts.pv,1):'',
    	        plugins:                           'viral-2',
    	        'viral.recommendations':            base_path+'rec',
    	        'viral.functions':                  'recommendations, embed, link',
    	        'viral.allowmenu':                  'true',
    	        'viral.onpause':                    'false', 
                'viral.link':                       base_path,
                'viral.email_subject':              'Check out this video: '+ v.Title,
                'viral.email_footer':               "-----\n\nVisit our main site at:\n\nhttp://"+xsUtil.getHostPath()+xs.path,
                'viral.fgcolor':                    "#ff0000",
                'viral.bgcolor':                    "#000000",
                'frontcolor':                       "#ffffff",
                "lightcolor":                       "#ff0000"  	        
    	    };
    	    
    	    
    	    var params= {
    	        allowfullscreen: 'true',
    	        allowscriptaccess: 'always',
    	        allownetworking: 'all',
    	        wmode: 'transparent'
    	    };
    	    var attributes = {
    	        id: target_embed,
    	        name: target_embed
    	    };
    	    if (!swfobject.hasFlashPlayerVersion("7")) { 
    	        var el = $(opts.target+'-box');
    	        if (el) el.setStyle({display:'none'});
    	        return;
    	    }
    	    swfobject.embedSWF(vd.path+vd.swf, target, vd.width, vd.height, "9", vd.path+vd.exp, flashvars, params, attributes);
	    }.bind(this));
	},
	fixURL: function(u, f) {
	    try {
	        if (u.substr(0,4).toLowerCase() == 'http') return u;
            u = xsUtil.getHostPath()+xs.path+(f?'photo':'video')+'/'+u;
        } catch(e) {}
	    return u;
	},
	drawRotator: function(opts) {
	    var flashvars = {
	        file: opts.path+opts.src,
	        width: opts.width,
	        height: opts.height,
	        shuffle: 'false',
	        shownavigation: 'false',
	        transition: 'fade',
	        overstretch: 'fit'
	    };
	    var params= {
	        allowfullscreen: 'true',
	        wmode: 'transparent'
	    };
	    var attributes = {
	        id: opts.target+'-embed',
	        name: opts.target+'-embed'
	    };
	    if (!swfobject.hasFlashPlayerVersion("7")) { 
	        var el = $(opts.target+'-box');
	        if (el) el.setStyle({display:'none'});
	        return;
	    }
	    swfobject.embedSWF(opts.path+opts.swf, opts.target, opts.width, opts.height, "7", opts.path+opts.exp, flashvars, params, attributes);
	},
	queueCoverFlow: function(opts) {
	    xs.register(this.drawCoverFlow.bind(this, opts), this);
	},
	drawCoverFlow: function(opts) {
	    var flashvars = { };
	    var params= {
	        allowfullscreen: 'true',
	        wmode: 'transparent',
	        allowscriptaccess: 'always'
	    };
	    var attributes = {
	        id: opts.target+'-embed',
	        name: opts.target+'-embed'
	    };
	    if (!swfobject.hasFlashPlayerVersion("7")) { 
	        var el = $(opts.target+'-box');
	        if (el) el.setStyle({display:'none'});
	        return;
	    }
	    swfobject.embedSWF(xsUtil.getHostPath()+'/'+opts.swf, opts.target, opts.width, opts.height, "7", opts.path+opts.exp, flashvars, params, attributes);
	},
	submitTo: function(k,u) {
	    var t = '';
	    switch (k) {
	        case 'myspace':
	            t = 'http://www.myspace.com/index.cfm?fuseaction=postto&u=';
	            break;
	        case 'facebook':
	            t = 'http://www.facebook.com/sharer.php?u=';
	            break;
	        case 'digg':
	            t = 'http://digg.com/submit?phase=2&url=';
	            break;
	        case 'del.icio.us':
	            t = 'http://del.icio.us/post?url=';
	            break;
	        case 'newsvine':
	            t = 'http://www.newsvine.com/_wine/save?u=';
	            break;
	        default:        
	    }
	    if (t) xsUtil.go(t+(u?u:document.location.href),true);
	    return false;
	},
	email: function(u) {
	    var url = "mailto:?subject=" + document.title + "&body=Hey,%0a%0aI thought you might be interested in this article:%0a%0a" + document.title + ".%0a%0aYou can view it at:%0a%0a" + (u?u:location.href);
        xsUtil.go(url);
	    return false;
	},
    ajaxReturn: function(req_obj, obj) {
        try {
            var response = obj?obj:eval('('+req_obj.responseText+')');
        } catch (e) { if (req_obj.responseText) { xsJSError(e); } return; }
        try {
            if (!isUndefined(response.Error)) {
                alert(response.Error);
            } else {
                if (!isUndefined(response.Message)) alert(response.Message);
                var ret = response.Ret;
                if (ret && this[ret+'_ret']) this[ret+'_ret'](response);
            } 
        } catch (e) { }
    }
};


var xsComments = {    
    Elements:{
        CmtName:{El:'Name', Placeholder:'Your Name'}, 
        CmtEmail:{El:'Email', Placeholder:'Your Email Address (will not be shown or shared)'},
        CmtBody:{El:'Body', Placeholder:'Your Comment (All comments subject to approval prior to appearing on site)'},
        CmtSubscribe:{El:'Subscribe'},
        CmtUserId:{El:'UserId'},
        CmtForm:{El:'Form'}
    },
    Box:'cmts-box',
    init: function() {
        $H(this.Elements).keys().each(function(k) {
            try { 
                var v = this.Elements[k];
                this[v.El] = $(k);
                if (v.Placeholder) this.focus(this[v.El], false);
            } catch (e) { }
        }.bind(this));
    },
	page: function(id, page) {
		new Ajax.Updater({success:this.Box}, xs.path+'id/'+id+'//0/cmt/page/'+page+'/');
		return false;
	},
	all: function(id) {
		new Ajax.Updater({success:this.Box}, xs.path+'id/'+id+'//0/cmt/all/');
		return false;	    
	},
	focus: function(el, f) {
	    var v = this.Elements[el.id];
	    if (!v.Placeholder) return;
	    
        if (f) {
            if (el.value && el.value == v.Placeholder) {
                el.value = '';
                el.removeClassName('inactive');
            }
        } else {
            if (!el.value || (el.value == v.Placeholder)) {
                el.addClassName('inactive');
                el.value = v.Placeholder;
            }
        }
	},
	focusAll: function(f) {
        $H(this.Elements).keys().each(function(k) {
            try { 
                var v = this.Elements[k];
                if (v.Placeholder) this.focus(this[v.El], f);
            } catch (e) { }
        }.bind(this));	    
	},
	save: function(a_id) {
	    try {
	        this.focusAll(true);
	        var user_id = parseInt(this.UserId.value);
            
            try { 

    	        if (!user_id && !xsValidate.test([
                        [this.Name, 'You must enter your name.'],
                        [this.Email, 'You must enter a valid email address.', {re:/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i}]
        		])) throw 1;

    			if (!xsValidate.test([
                    [this.Body, 'You must enter a comment to post.']
    			])) throw 1;


    	        var query = {validator:'Comments', Act:'save', Ret:'save', Bg:1, ArticleId:a_id, Body:this.Body.value};
	            
    	        if (!user_id) Object.extend(query, {Name:this.Name.value, Email:this.Email.value, Subscribe:this.Subscribe.value});
	        
                new Ajax.Request(xs.save, {parameters:$H(query).toQueryString(), onSuccess:this.ajaxReturn.bind(this)});   
            } catch (e) {
                this.focusAll(false);
                return false;
            }
	        
	    } catch (e) { xsJSError(e); }
	    return false;
	},
	save_ret: function(response) {
	    this.Form.reset();
	    this.focusAll(false);
	    if (response.Show) this.page(response.ArticleId,0);
	},
	edit: function(el) {
        var c_id = xsUtil.getEventId(el);
        if (!c_id) return;	    
	    xsUtil.go(xs.path+'admin/comments/'+c_id+'/edit/');
	    return false;
	},
    ajaxReturn: function(req_obj, obj) {
        try {
            var response = obj?obj:eval('('+req_obj.responseText+')');
        } catch (e) { if (req_obj.responseText) { xsJSError(e); } return; }
        try {
            if (!isUndefined(response.Error)) {
                xsMsg.alert(response.Error);
            } else {
                if (!isUndefined(response.Message)) xsMsg.alert(response.Message);
                var ret = response.Ret;
                if (ret && this[ret+'_ret']) this[ret+'_ret'](response);
            } 
        } catch (e) { }
    } 
};


var xsSkunk2 = {
	menu: function() {
        if(navigator.appVersion.indexOf("MSIE")==-1){return;}
        var i,k,g,lg,r=/\s*p7hvr/,nn='',c,cs='p7hvr',bv='menu';
        for(i=0;i<10;i++){g=document.getElementById(bv+nn);if(g){
            lg=g.getElementsByTagName("LI");
            if(lg){for(k=0;k<lg.length;k++){
                lg[k].onmouseover=function(){c=this.className;cl=(c)?c+' '+cs:cs;this.className=cl;};
                lg[k].onmouseout=function(){c=this.className;this.className=(c)?c.replace(r,''):'';};}
            }
        }nn=i+1;}
    }
};
