/**************************************************************
	Script		: DrupalSite
	Version		: 1.0
	Authors		: Pieter Soudan
	Desc		: a DrupalSite Class for controlling all JS functionality for a Drupal Site
	Licence		: property of Red & Ivory
**************************************************************/

var DrupalSite = new Class({
    Implements: Options,
    options: {
	autoloop: false,
	animate: false,
	publicdir: 'publicdir',
	assetsdir: 'assetsdir',
	colorview: 'colorview',
	debugcntnr: 'debugmode',
	pagename: 'default',
	pagetype: 'default',
	profile: 'normal',
	debugmode: false,
	delay:6000
    },
    
    initialize: function(options){
	
	this.loopers = [];
	this.timer = new Hash();
	
	this.setOptions(options);
	this.assetsdir = this.options.assetsdir;
	this.publicdir = this.options.publicdir;
	this.colorview = this.options.colorview;
	
        Browser.ie6 = (Browser.Engine.trident && Browser.Engine.version == 4);
	window.ie6 = Browser.ie6;
	
	if(this.options.debugmode) {
	    if(!window.console){
		//this.debugscreen = new DebugScreen({position:'bottomLeft'});
	    }
	    this.debug('*** DEBUG MODUS ***');
	}
	/*
	if($('datumveld')){
	   myCal = new Calendar({ day1: 'd/m/Y' }, { navigation: 2 });
	}
	*/
	//new SmoothScroll({ duration:700 }, window);
	
	if(this.options.debugmode){
	    this.debugmode();
	}
    },
    
    start:function(){
	if(this.options.debugmode) this.logTimer('drupalsite_start');
	//this.initPreloader();
	
	if(Browser.ie6) this.doIE6stuff();
	if(this.options.scriptactions.contains('rating')) this.initRatingWidget();
	if(this.options.scriptactions.contains('hovers')) this.initHoverImages();
	if(this.options.scriptactions.contains('links')) this.initLinks();
	if(this.options.scriptactions.contains('photomasks')) this.initPhotomasks();
	if(this.options.scriptactions.contains('stickies')) this.initStickies();
	if(this.options.scriptactions.contains('tooltips')) this.initTooltips();
	if(this.options.scriptactions.contains('galleries')) this.initGalleries();
	if(this.options.scriptactions.contains('clips')) this.initClips();
	if(this.options.scriptactions.contains('progressbars')) this.initProgressBars();
	if(this.options.scriptactions.contains('shoutbox') && this.options.loggedin)  this.initShoutbox();
	if(this.options.scriptactions.contains('scorner')) this.initScorner();
	if(this.options.scriptactions.contains('gameselector')) this.initGameselector();
	if(this.options.scriptactions.contains('alertbox'))this.initAlertbox();
	if(this.options.scriptactions.contains('SqueezeBox'))this.initSqueezeBox();
	if(this.options.scriptactions.contains('alphabetic'))this.alfabeticchildcheck();
	if(this.options.debugmode)this.logTimer('drupalsite_start');
    },
    
    alfabeticchildcheck:function(){
	this.container = $$('.alfa');
	if(this.container){
	     this.container.each(function(el,i){ 
		  var children = el.getChildren('<div class="link">')  
		  if(children[2]){
		       
		  }else{
		      el.setStyle('display','none');
		  } 
	     });
	}
     
    },	
    
    startLoop: function(){
	this.loop = this.switchAll.periodical(this.options.delay, this);
    },
    
    stopLoop: function(){
	$clear(this.loop);
    },
    
    switchAll: function(){
	var i=0;
	var nbLoops = this.loopers.length;
	for(i=0; i<nbLoops;i++){
	    this.loopers[i].switchMe();
	}
    },
    
    addLooper: function(l){
	this.loopers.push(l);
    },
    
    doIE6stuff: function(){
	
    },
    
    initAlertbox: function(){
	if ($('resultalert')){
	    Sexy = new SexyAlertBox();
	    if($('resultalert').getProperty('title') == "error"){
		Sexy.error($('resultalert').getProperty('rel'));
	    } else	{
		Sexy.info($('resultalert').getProperty('rel'));
	    }
	}
    },
    
    initSqueezeBox:function(){
	SqueezeBox.assign($$('a[rel=boxed][href^=#]'), {
	    size: {x: 320, y: 250}
	});
    },
    
    initProgressBars: function(){
	//alert('1');
	$$('.progressbar').each(function(el, i){
	    pb = new dwProgressBar({
		container: el,
		startPercentage: el.getProperty('rel'),
		speed:1000,
		boxID: 'box_'+el.getProperty('id'),
		percentageID: 'perc_'+el.getProperty('id'),
		step:100,
		allowMore: 1
	    });
	},this);
    },
    
    initShoutbox: function(){
	options = {};
	$$('.shoutbox').each(function(el,i){
	    this.createShoutbox(el, options);
	}, this);
    },
    
    initPreloader: function(){
	this.preloader = new Preloader({position:'bottomRight'});
    },
    
    createShoutbox: function(el, options){
	if(!this.shoutboxes) this.shoutboxes = new Array();
	var s = new Shoutbox(el, options);
	this.shoutboxes.push(s);
	return s;
    },
    
    debugmode: function(){
	this.debug('DEBUG [nb of DOM elements: '+document.getElementsByTagName('*').length+']');
    },
    
    hoverItem: function(item){
	item.addClass('hover');
    },
    unhoverItem: function(item){
	item.removeClass('hover')
    },

    createGalleryTeaser: function(feat, options){
	if(!this.gteasers) this.gteasers = new Array();
	var c = new GalleryTeaser(feat, options);
	this.gteasers.push(c);
	return c;
    },
    
    createStickyList: function(list, options){
	if(!this.stickylists) this.stickylists = new Array();
	var sl = new StickyList(list, options);
	this.stickylists.push(sl);
	return sl;
    },

    createRatingWidget: function(widget, options){
	if(!this.ratingwidgets) this.ratingwidgets = new Array();
	var rw = new RatingWidget(widget, options);
	this.ratingwidgets.push(widget);
	return rw;
    },

    createGallerySwitcher: function(display, options){
	if(!this.galleryswitchers) this.galleryswitchers = new Array();
	var c = new GallerySwitcher(display, options);
	this.galleryswitchers.push(c);
	return c;
    },
    
    createClip: function(cl, options){
	if(!this.clips) this.clips = new Array();
	var c = new Clip(cl, options);
	this.clips.push(c);
	return c;
    },
    
    initSifr: function(){},
    makeGallery: function(classn, namse){},
    initLinks: function (){},
    
    initPhotomasks: function(){
	$$('.photomask').each(function(el, i){
	    var r = el.getProperty('rel');
	    var t = el.getProperty('dir');
	    if(r) {
		el.setStyle('cursor', 'pointer');
		if(t){
		    el.addEvent('click', this.openNewWindow.bind(this, [r]));
		} else {
		    el.addEvent('click', function(){window.location = r});
		}
	    }
	    
	}, this);
    },
    
    initStickies: function(){
	options = {
	    slideTimer: 6000, 
	    items: '.sticky-item',
	    autoloop: true,
	    animate: this.options.animate
	}
	$$('.sticky-list').each(function(slist,i){
	    this.createStickyList(slist, options);
	}, this);
    },
    
    initRatingWidget: function(){
	$$('.ratingwidget').each(function(el, i){
	    this.createRatingWidget(el);
	}, this);
    },

    initClips: function(){
	$$('.rnim_clip').each(function(el, i){
	    this.createClip(el, {});
	}, this);
    },
    
    initTooltips: function(){
        //store titles and text
        $$('.tipme').each(function(element,index) {
	    var content = element.get('title');
            if(content) {
		content = content.split('::');
		if(content[0] && content[1]){
		   element.store('tip:title', content[0]);
		   element.store('tip:text', content[1]);
		}
		else if(content[0]){
		    element.store('tip:title', '');
		    element.store('tip:text', content[0]);
		} else  {
		    element.store('tip:title', '');
		    element.store('tip:text', '');
		}
	    }
        });
        
        //create the tooltips
        var tipz = new Tips('.tipme',{
            className: 'tipme',
            fixed: false,
            hideDelay: 50,
            showDelay: 50
        });
        
    },
    
    initGalleries: function(){
	$$('.thumbnail').each(function(el, i){
	    el.addEvents({
		'mouseenter':function(e){
		    el.addClass('active')
		},
		'mouseleave':function(e){
		    el.removeClass('active');
		}
	    });
	});
	
	$$('.gallery_switcher').each(function(gs, i){
	    this.createGallerySwitcher(gs);
	}, this);
    },
    
    initHoverImages: function(){
	$$('.hoverimg').each(function(el, i){
	    var src = el.getProperty('src');
	    if(!src) {
		src = el.getStyle('background-image');
		src = src.slice(src.indexOf('url(')+4,src.length-1);
		el.backg = 1;
	    } else el.backg = 0;
	    
	    el.ext = src.slice(src.indexOf('_r.')+2,src.length);
	    el.src_h = src.replace('_r'+el.ext,'_h'+el.ext);
	    el.src_r = src.replace('_h'+el.ext,'_r'+el.ext);
	    
	    el.addEvents({
		'mouseenter':function(e){
		    if(el.backg) el.setStyle('background-image', 'url('+el.src_h+')');
		    else el.setProperty('src',el.src_h);
		},
		'mouseleave':function(e){
		    if(el.backg) el.setStyle('background-image', 'url('+el.src_r+')');
		    else el.setProperty('src',el.src_r);
		    //el.setProperty('src',el.getProperty('src').replace('h'+el.ext,'r'+el.ext));
		}
	    });
	});
    },
    
    doPngFixes: function(){          
	if($('header_logo')){
	    $('header_logo').getElement('img').addClass('fixPNG');
	}
	$$('.fixPNG','.photoMask','.photomask','.indicator').each(function(el ,i){
	    Browser.fixPNG(el);
	})
    },
    
    debug: function(msg){
	if(this.options.debugmode) {
	    if(window.console){
		window.console.log(msg);
	    }
	    else {
		$('debugmode').set('html', $('debugmode').get('html')+'<br/>'+msg);
	    }
	}
    },
    
    openNewWindow: function(href){
	window.open(href,'new_window') ;
    },
    
    logTimer: function(uid){
	if(this.options.debugmode){
	    if (!this.timer.has(uid)) {
		this.timer.set(uid, []);
	    }
	    this.timer.get(uid).push($time());
	}
    },
    
    visualizeTimer: function(){
	this.timer.each(function(el, i){
	    this.debug(i);
	    first = 0;
	    $A(el).each(function(tm, j){
		if(first==0) first = tm;
		else {
		    this.debug(tm - first);
		}
	    });
	}, this);
    },
    
    replyComment: function(id, btn, btncntnr){
	var pos = btncntnr.indexOf('_');
	var cid = btncntnr.slice(0,pos);
	var nid = btncntnr.slice(pos+1);
	var container = $(id);
	
	$(btncntnr).getElement(btn).destroy();
	
	var form = new Element('form', {
	    id:'form_'+id,
	    action:'?',
	    method:'POST'
	    });
	
	var action = new Element('input',{
	    type: 'hidden',
	    name: 'action',
	    value: 'replycomment'
	});
	var unique = new Element('input',{
	    type: 'hidden',
	    name: 'unique',
	    value: site.constructKeycode()
	});
	
	var commentid = new Element('input',{
	    type: 'hidden',
	    name: 'commentid',
	    value: cid
	});
	
	var nodeid = new Element('input',{
	    type: 'hidden',
	    name: 'nodeid',
	    value: nid
	});
	
	var texta = new Element('textarea',{
	    name: 'comment',
	    id: 'textarea_'+id
	});
	var submit = new Element('input',{
	    type: 'submit',
	    'class': 'postcomment',
	    id: 'textarea_'+id,
	    value:'post comment'
	});
	form.adopt(unique,action,commentid,nodeid,texta,submit);
	
	form.replaces(container);
	
	//replace textarea
	var oFCKeditor = new FCKeditor( 'textarea_'+id ) ;
	oFCKeditor.ToolbarSet = 'MyToolbar1';
        oFCKeditor.BasePath = site.options.publicdir+"backend/modules/fckeditor/fckeditor/";
	oFCKeditor.ReplaceTextarea();
	
    },
    
    editComment: function(id, btn){
	var pos = id.indexOf('_');
	var cid = id.slice(0,pos);
	var nid = id.slice(pos+1);
	var container = $(id);
	
	container.getElement(btn).destroy();
	var text = container.getElement('.text');
	
	var form = new Element('form', {
	    id:'form_'+id,
	    action:'?',
	    method:'POST'
	    });
	
	var action = new Element('input',{
	    type: 'hidden',
	    name: 'action',
	    value: 'editcomment'
	});
	var unique = new Element('input',{
	    type: 'hidden',
	    name: 'unique',
	    value: site.constructKeycode()
	});
	
	var commentid = new Element('input',{
	    type: 'hidden',
	    name: 'commentid',
	    value: cid
	});
	var nodeid = new Element('input',{
	    type: 'hidden',
	    name: 'nodeid',
	    value: nid
	});
	var texta = new Element('textarea',{
	    name: 'comment',
	    id: 'textarea_'+id
	});
	var submit = new Element('input',{
	    type: 'submit',
	    'class': 'postcomment',
	    id: 'textarea_'+id,
	    value:'edit comment'
	});
	form.adopt(unique,action,commentid,nodeid,texta,submit);
	
	var t = text.get('html');
	texta.set('value', t);
	form.replaces(text);
	
	//replace textarea
	var oFCKeditor = new FCKeditor( 'textarea_'+id ) ;
	oFCKeditor.ToolbarSet = 'MyToolbar1';
        oFCKeditor.BasePath = site.options.publicdir+"backend/modules/fckeditor/fckeditor/";
	oFCKeditor.ReplaceTextarea();
    },
    
    editGuestbookEntry: function(id, btn){
	var gid = id.slice(id.lastIndexOf('_')+1);
	var container = $(id);
	
	container.getElement(btn).destroy();
	var text = container.getElement('.text');
	
	var form = new Element('form', {
	    id:'form_'+id,
	    action:'?',
	    method:'POST'
	    });
	
	var action = new Element('input',{
	    type: 'hidden',
	    name: 'action',
	    value: 'editguestbookentry'
	});
	var unique = new Element('input',{
	    type: 'hidden',
	    name: 'unique',
	    value: site.constructKeycode()
	});
	
	var gbid = new Element('input',{
	    type: 'hidden',
	    name: 'gbid',
	    value: gid
	});
	var texta = new Element('textarea',{
	    name: 'comment',
	    id: 'textarea_'+id
	});
	var submit = new Element('input',{
	    type: 'submit',
	    'class': 'postcomment',
	    id: 'textarea_'+id,
	    value:'post comment'
	});
	form.adopt(unique,action,gbid,texta,submit);
	
	var t = text.get('html');
	texta.set('value', t);
	form.replaces(text);
	
	//replace textarea
	var oFCKeditor = new FCKeditor( 'textarea_'+id ) ;
	oFCKeditor.ToolbarSet = 'MyToolbar1';
        oFCKeditor.BasePath = site.options.publicdir+"backend/modules/fckeditor/fckeditor/";
	oFCKeditor.ReplaceTextarea();
    },
    
    constructKeycode: function(){
	return $random(0,99999);
    },
    
    initScorner: function(){
	
	var game_cntnr = $('scorner_game');
	debug(game_cntnr);
	if(game_cntnr){
	    flashvars = {
	    'g': scorner_options.code,
	    'ASSETS': scorner_options.assets,
	    'SERVER': scorner_options.root,
	    'DIR': scorner_options.assets+'scorner/',
	    'SITE': scorner_options.site,
	    'LANG': scorner_options.lang,
	    'PREROLL': scorner_options.preroll,
	    'PREROLL_TYPE': scorner_options.prerolltype,
	    'POSTROLL': scorner_options.postroll,
	    'USERID': scorner_options.userid,
	    'DEBUG': this.options.debugmode?1:0
	    };
	    addFlash('scorner_game_flash', scorner_options.assets+'scorner/loader.swf',flashvars, 600,450);
	}
    },
    
    
    
    initGameselector: function(){
	//alert('test');
	options:{};
	
	$$('.gameselector').each(function(disp,i){
	    this.createGameselector(disp,options);
	},this);
    },
    
    createGameselector: function(disp,options){
	if(!this.disp) this.disp = new Array();
	var c = new GameSelector(disp, options);
	return c;
    }
});

//guarantee singleton
var site;
function createDrupalSite(options){
    site = new DrupalSite(options);
}

function debug(msg){
    if(site) site.debug(msg);
}

function clone(obj){
    if(obj == null || typeof(obj) != 'object')
        return obj;

    var temp = new obj.constructor(); // changed
    for(var key in obj)
        temp[key] = clone(obj[key]);
    return temp;
}