Array.prototype.cleanWhitespace = function () {
    for (var l = this.length; l > -1; l -= 1) {
	    if (this[l] === '') {
		    this.splice(l, 1);
	    }
    }
};
       
String.prototype.caseCompare = function (str) {
    if (this.toLowerCase() === String(str).toLowerCase()) {
	    return 0;
    } else {
	    return 1;
    }
};

YUI.add('site-controller', function (Y) {
    Y.SiteController = function (connector) {
	    this.poster_state = 'UNCOVERED';
	    this.content_state = 'INITIALIZE';
	    this.page_type = 'page';
	    this.content = '';
	    this.dom = 'loading';
	    this.connector = connector;
	    this.saved_path = -1;
	    this.default_path = -1;
	    this.items = [];
	    this.dataSource = new Y.DataSource.IO({
			source: server + loc + "/ajax.php",
			method: 'POST',
			headers: {'Content-type': 'application/x-www-form-urlencoded; charset=utf-8'}
	    });
	    
	    this.slideshow = Y.Slideshow;
	    this.slideshowNavigator = Y.SlideshowNavigator;
    };
    
    Y.SiteController.prototype.domReady = function () {
	    this.view = Y.one('#view');
	    Y.on('click', this.handleClick, '#menu', this);
	    this.items[0] = {};
	    this.items[0].items = Y.all('#menu li');
	    this.items[0].links  =  Y.all('#menu a');
	    this.default_path = this.items[0].links.item(1).get('href').split(server + loc)[1].split('/');
	    this.default_path.cleanWhitespace();
	    this.initializeUrl();
    };
    
    Y.SiteController.prototype.initializeUrl = function () {
	    if (this.dom === 'ready' &&  this.default_path !== -1) {
		    this.handleUrl(((this.saved_path.length) ? this.saved_path : []));
	    }
    };
    
    Y.SiteController.prototype.handleClick = function (e) {
	    var a, href, data;
	    e.preventDefault();
	    a = ((e.target.get('tagName') === 'A') ? e.target: e.target.ancestor('a'));
	    if (a) {
		    
		    href =  String(a.get('href')).split(server + loc)[1];//.split('/').join('');
		    //if (href) {
			SWFAddress.setValue(href);
		    //}
	    }
	    
    };
    
    
    // handle loaction bar changes
    
    Y.SiteController.prototype.handleUrl = function (path) {
	    var i,
		n = -1,
		match = -1,
		it = -1,
		l = 0,
		p = '';
	    
	    if (this.dom === 'ready') {
		    l = path.length;
		    for (i = 0; i < l; i += 1) {
			    p = ((i) ? p + '/' + path[i] : path[i]);
			    match = this.match(p, this.items[i].links);
			    if (match > -1) {
				    it = match;
				    n = i;
			    } else {
				    break;
			    }
		    }
		    
		    switch (n) {
			case 0:
			    this.page_type = 'page';
			    this.content_state = 'LOADING';
			    this.loadPage(path[0], 'page');
			    this.connector.notifyConnections('load_content', this, '');
			    this.deactivate(0);
			    if (this.items.length > 1) {
				    this.deactivate(1);
			    }
			    this.activate(this.items[0].items.item(it - 1));
			    this.view.ancestor().set('scrollTop',0);
			    break;
			case 1:
			    this.page_type = 'subpage';
			    this.content_state = 'LOADING';
			    this.loadPage(path[1], 'prog');
			    this.connector.notifyConnections('load_content', this, '');
			    this.view.ancestor().set('scrollTop',0);
			    if (this.items.length > 1) {
				    this.deactivate(1);
			    }
			    //Y.log()
			    this.activate(this.items[1].items.item(Math.floor(it / 2)));
			    break;
			case -1:
			    this.page_type = 'default';
			    this.content_state = 'LOADING';
			    this.loadPage(this.default_path, 'page');
			    this.connector.notifyConnections('load_content', this, '');
			    this.view.ancestor().set('scrollTop',0);
			    this.deactivate(0);
			    if (this.items.length > 1) {
				    this.deactivate(1);
			    }
			    break;
		    }
	    } else {
		    this.saved_path = path;
		    this.initializeUrl();
	    }
    };
    
    Y.SiteController.prototype.receive = function (e, argv) {
	    switch (e) {
		case 'swf_ready':
		    this.dom = 'ready';
		    this.initializeUrl();
		    break;
		case 'swf_resize':
			this.view.setStyle('height', argv.h + 'px');
			break;
		case 'is_covered':
			this.poster_state = "COVERED";
			this.updatePage(this.content);
			break;
		case 'is_uncovered':
			this.poster_state = "UNCOVERED";
			break;
	    }
    };
    
    
//    Y.SiteController.prototype.match = function (path, items) {
//	    
//		items.some(function(item,n){
//		    var href = String(item.get('href')).split(server + loc)[1].split('/').join('');
//		    if (href.caseCompare(path) === 0) {
//			    this.content_state = 'LOADING';
//			    this.loadPage(href, 'page');
//			    this.connector.notifyConnections('load_content', this, '');
//			    //this.deactivate();
//			   // this.activate(this.menuItems.item(n));
//			    return true;
//		    } else {
//			    return false;
//		    }
//    		},this);
//    };
    
    
    Y.SiteController.prototype.match = function (path, items) {
	    var m, n;
	    
	    m = -1;
	    
	    items.some(function (item, n) {
		    var href = String(item.get('href')).split(server + loc)[1];
		    href  = href.substring(1, href.length - 1);
		    if (href.caseCompare(path) === 0) {
			    m = n;
			    return true;
		    } else {
			    return false;
		    }
	    });
	    
	    return m;
    };
    
    Y.SiteController.prototype.loadPage = function (path, tb) {
	    var that = this;
	    this.dataSource.sendRequest("?cmd=page&page=" + path + "&tb=" + tb,  {
			success: function (e) {
				that.updatePage(e.response.results[0].responseText);
			},
			failure: function (e) {
			    alert("Could not retrieve data: " + e.error.message);
			}
	    });
    };
     
    Y.SiteController.prototype.updatePage = function (content) {
	    var cols, x;
	    if (this.poster_state === 'COVERED') {

		    if (this.page_type === 'page' || this.page_type === 'default') {
			    this.view.set('innerHTML', '');
			    this.view.setContent(content);
		    } else {
			    cols = this.view.all('.c1');
			    if (cols.size() > 1) {
				    cols.item(1).remove();
			    }
			    this.view.append(content);
		    }
		    x = 60 + ((this.page_type === 'default') ? 20 : this.view.all('.c1').size() * 350);
		    this.content_state = "LOADED";
		    this.content = '';
		    this.connector.notifyConnections('content_loaded', this, {x: x});
		    this.activatePage();
	    } else {
		    this.content = content;
		    this.content_state = "WAITING";
	    }
     
    };
     
    Y.SiteController.prototype.activate = function (ob) {
		//Y.log(ob);
		ob.addClass('active');
	};
	
	Y.SiteController.prototype.deactivate = function (n) {
		this.items[n].items.removeClass('active');
	};
	
	Y.SiteController.prototype.activatePage = function () {
		var SlideshowContainer = this.view.one('.slideshow'),
		    multi = this.view.one('.multi'),
		    cap,
		    slides;
	   
		if (SlideshowContainer) {
			SlideshowContainer.setStyles({overflow: 'hidden'});
			slides = [];
			SlideshowContainer.all('.slide').each(function (slide) {
				slides.push(Y.JSON.parse(slide.one('input').get('value')));
				slide.remove();
			});
			cap = SlideshowContainer.next('.cap');
			this.slideshow.set(this.connector, SlideshowContainer, cap, server + SlideshowContainer.one('input').get('value'), slides, {});
			if (slides.length > 1) {
				this.slideshowNavigator.set(this.connector, this.slideshow, SlideshowContainer, 0, slides.length);
			}
		}
		
		if (multi) {
			this.items[1] = {};
			this.items[1].links = multi.all('a');
			this.items[1].items = multi.all('.rw');
			Y.on('click', this.handleClick, multi, this);
		}
	};
});



YUI.add('connector', function (Y) {
    Y.Connector = function () {
	    this.obs = [];
	    this.events = [];
    };
    
    Y.Connector.prototype.getObj = function (ob) {
	    var i;
		for (i = 0; i < this.obs.length; i += 1) {
			if (this.obs[i] === ob) {
				return i;
			}
		}
		return -1;
    };
    
    Y.Connector.prototype.addConnection = function (ob, e, connection) {
	    var i, n;
	    n = this.getObj(ob);
	    if (n < 0) {
		    this.obs.push(ob); // myController
		    n = this.obs.length - 1;
		    this.events[n] = {};
	    }
	    
	    for (i = 0; i < e.length; i += 1) {
		    if (!this.events[n][e[i]]) {
			    this.events[n][e[i]] = []; //['all']
		    }
		
		    this.events[n][e[i]].push(connection); // myItems
	    }    
	    
    };
		
    Y.Connector.prototype.notifyConnections = function (e, caller, argv) {
	    var n = this.getObj(caller);
	    
	    if (n > -1) {
		    if (this.events[n].all) {
			    this.connectionNotify(this.events[n].all, e, argv);
		    }
		    if (this.events[n][e]) {
			    this.connectionNotify(this.events[n][e], e, argv);
		    }
	    }
    };

    Y.Connector.prototype.connectionNotify = function (connections, e, argv) {
	    var i;
	    for (i = 0; i < connections.length; i += 1) {
		    connections[i].receive(e, argv);
	    }	
    };
});

YUI.add('swf-poster', function (Y) {
    Y.SwfPoster = function (connector, id, params) {
	    this.connector = connector;
	    this.view = this.addView(id, params);
	    this.container = Y.one('#' + id);
	    this.resize();
    };
    
    Y.SwfPoster.prototype.addView = function (id, params) {
	    var mySWF = new YAHOO.widget.SWF(id, server + loc + '/swf/poster.swf' + "?nocache=" + new Date().getTime(), params);
	    mySWF.pr = this;
	    
	    mySWF.subscribe('swfReady', function () {
		    this.pr.swfReady();
	    });
	    
	    mySWF.subscribe('covered', function () {
		    this.pr.isCovered();
	    });
	    
	    mySWF.subscribe('uncovered', function () {
		    this.pr.isUncovered();
	    });
	    
	    mySWF.subscribe('swfResize', function (e) {
		    this.pr.swfResize(e.h);
	    });
	    
	    mySWF.subscribe('goArt', function () {
		    this.pr.goArt();
	    });
	    
	    return mySWF;
	
    };
    
    Y.SwfPoster.prototype.goArt = function () {
	    SWFAddress.setValue("/programma/");//Jeroen_Doorenweerd/
   
    };
    
    Y.SwfPoster.prototype.isCovered = function () {
	    //this.container.setStyle('left', this.view.callSWF('reset_left') + 140 +'px');
	    this.connector.notifyConnections('is_covered', this, {});
    };
    
    Y.SwfPoster.prototype.isUncovered = function () {
	    this.container.setStyle('width', (this.container.get('winWidth') - (this.view.callSWF('reset_left') + 140)) + 'px');
	    this.connector.notifyConnections('is_uncovered', this, {});
    };
    
    Y.SwfPoster.prototype.swfReady = function () {
	    this.connector.notifyConnections('swf_ready', this, {});
	    this.resize();
	   
    };
    
    Y.SwfPoster.prototype.swfResize = function (h) {
	   
	   // this.container.setStyle('height', h + 'px');
	    //this.receive('load_content', {});
    };
    
    
    Y.SwfPoster.prototype.receive = function (e, argv) {
	    
	    switch (e) {
		case 'load_content':
		    this.view.callSWF('cover', [(this.container.get('region').left - 140)]);
		    this.container.setStyle('width', (this.container.get('winWidth') - 140) + 'px');
		    break;
		case 'content_loaded':
		    this.view.callSWF('uncover', [argv.x]);
		    break;
	    }
    };
    
    Y.SwfPoster.prototype.resize = function () {
	    var h = this.view.callSWF('Resize', [this.container.get('winWidth') - 140, this.container.get('winHeight')]);
	    if(parseInt(h) > 0 ) {
		    this.container.setStyle('height', h + 'px');
		    this.connector.notifyConnections('swf_resize', this, {h: h});
	    }
    };
});








YUI().use('node', 'event', "anim", 'json-parse', 'connector', "datasource-io", 'site-controller', 'swf-poster', 'slideshow', 'slideshow-buffer', 'slideshow-display', 'slideshow-navigator', function (Y) {
    var myConnector, mySiteController, params;
    myConnector = new Y.Connector();
    mySiteController = new Y.SiteController(myConnector);
    
    params = {version: 9.115,
		useExpressInstall: false,
		allowScriptAccess: "allways",
		fixedAttributes: {
		    wmode: 'transparent',
		    scale: "noscale",
		    salign: "TL",
		    bgcolor: '#ffffff'
		}
	    };
    SWFAddress.addEventListener(SWFAddressEvent.CHANGE, handle_url);
    
    function handle_url(e) {
	    var path = String(e.path).split('/');
	    path.cleanWhitespace();
	    mySiteController.handleUrl(path);
    }
    
    Y.on('load', function () {
	
	    Y.log('domready');
	   
	    var swfBG,
		mySwfPoster,
		mySlideshow,
		mySlideshowNavigator;
	    
	   
	    swfBG =  new YAHOO.widget.SWF('background', server + loc + '/swf/background.swf?nocache=' + new Date().getTime(), params);

	    mySwfPoster = new Y.SwfPoster(myConnector, 'poster', params);
	    mySiteController.domReady();
	    myConnector.addConnection(mySiteController, ['all'], mySwfPoster);
	    myConnector.addConnection(mySwfPoster, ['all'], mySiteController);
	    //
	    //Y.on('resize',  mySwfPoster.resize, window, mySwfPoster);
	   
    });
});



    

    

