/***************************************************************
*  Copyright notice
*
*  (c) 2007 Sven Waechli (sven@screenteam.ch)
*  All rights reserved
*
*  This script is part of the TYPO3 project. The TYPO3 project is
*  free software; you can redistribute it and/or modify
*  it under the terms of the GNU General Public License as published by
*  the Free Software Foundation; either version 2 of the License, or
*  (at your option) any later version.
*
*  The GNU General Public License can be found at
*  http://www.gnu.org/copyleft/gpl.html.
*
*  This script is distributed in the hope that it will be useful,
*  but WITHOUT ANY WARRANTY; without even the implied warranty of
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*  GNU General Public License for more details.
*
*  This copyright notice MUST APPEAR in all copies of the script!
***************************************************************/
/**
 * @author	Sven Waechli	<sven@screenteam.ch>
 * @author	Mario Rimann	<typo3-coding@rimann.org>
 */

function startSwAjax() {
	getElementsByClassNameAndReplace("ajaxLink");
	getElementsByClassNameAndReplace("ajaxLink1");
	getElementsByClassNameAndReplace("ajaxLink2");
	initialize();
	checkBookmarkedVisit();
}


/** RSH Framework (to enable History and Bookmarks) **/
function initialize() {// initialize the DHTML History framework (dhtmlHistory.js)
	dhtmlHistory.initialize();// subscribe to DHTML history change events
    dhtmlHistory.addListener(historyChange);
}
         
/** callback to receive history change events. */
function historyChange(idParams) {
	if(idParams){
		// changed by rafi
		//newLocation='index.php?id='+idParams;
		newLocation=idParams;
		// end changed by rafi
		location.href = newLocation;
		/*location.href = idParams; */ //use this if staticDocuments is activated
	}
}	 
/** END RSH Framework (to enable History and Bookmarks) **/	

function checkBookmarkedVisit(){//svens workaround for bookmark visits
	if(window.location.hash){
		var hashString= window.location.hash;
		var idParams=hashString.replace(/#/,"");
		// changed by rafi
		//var newLocation='index.php?id='+idParams;
		var newLocation='http://'+window.location.hostname+'/'+idParams;
		// end changed by rafi
		/*var newLocation='http://yourdomain.tld/'+idParams;*///use this if simulateStaticDocuments is activated
		location.href = newLocation;
	}
}

/**  Change normal links on page into Ajax links **/ 
function getElementsByClassNameAndReplace(c){//t for filtering tags, not necessary
	var tags=document.getElementsByTagName("*");
	for(var i=0, len= tags.length; i<len; i++) {
		if (tags[i].className==c) {
			linkvar=tags[i].firstChild.getAttribute("href");
			// changed by rafi
			// check if link is already changed to ajax link
			if(linkvar!='javascript:void(0);') {
				// change link
				linktext=tags[i].firstChild.firstChild.nodeValue;
				tags[i].innerHTML='<a href="javascript:void(0);" onClick=\"javascript:sndReq(\''+linkvar+'\',\''+c+'\')\;\">'+linktext+'</a>';
			}
			// end changed by rafi
		}
	}	
}
/** END Change normal links on page into Ajax links **/ 

/** Change partial page content with Ajax **/ 
function getXMLHttpRequest()
{
		if (window.XMLHttpRequest){
			//XMLHttpRequest for Firefox, Opera, Safari, ev. IE7
			return new XMLHttpRequest();
		} else
		if (window.ActiveXObject){
			try{
				//XMLHttp (new) for IE
				return new ActiveXObject("Msxml2.XMLHTTP");
			} 	catch(e) {
				try{
					//XMLHttp (old) for IE
					return new ActiveXObject("Microsoft.XMLHTTP");
				} 	catch(e){
					return null;
				}
			}
		}
		return null;
}
									
var resObjekt;
	resObjekt = getXMLHttpRequest();
	
// changed by rafi
var ajaxTarget = 1;
// end changed by rafi

function sndReq(linkvar,c) {
	// changed by rafi
	// open the box
	// select target in that box to load content
	if (c=="ajaxLink1") {
		// second box
		showbox(2,-50,100);
		ajaxTarget=2;	
	} else if (c=="ajaxLink2") {
		// third box
		showbox(3,140,150);
		ajaxTarget=3;
	} else {
		// first box
		showbox(1,200,60);
		ajaxTarget=1;
	}
	// open the box
	
	// load content
	//
	test = /\?id=/.test(linkvar);//regex test: is ?id= substring of linkvar?
	if(test){//simulateStaticDocuments is NOT activated
		var stringArray = linkvar.split('?id=');	
		var idParams = stringArray[1];
	} else if(!test){//simulateStaticDocuments IS activated
		test2 = /\http/.test(linkvar);//regex test: is / a substring of linkvar?
		if(test2){//linkvar is complete link (IE)
			var stringArray = linkvar.split('/');
			var lastPos=(stringArray.length)-1;
			//alert(stringArray[lastPos-1]);
			idParams = stringArray[lastPos-1]+"/";
		}else
		if(!test2){//linkvar is NOT complete link (Firefox etc)
			idParams=linkvar;
		}
	}
	
	//return false;
	// end changed by rafi
	dhtmlHistory.add(idParams, true);//RSH framework, extract page id and add to history-->enables backbutton+history	
	
	//*********** overall object detection at the start of the script *****************
	var supportCheck=document.createElement && document.getElementsByTagName && getXMLHttpRequest();
	if(!supportCheck) return;
	//*********** END overall object detection at the start of the script *************
	//resObjekt.open('get','typo3conf/ext/tut_unobtrusiveajax/media/parserscript.php?linkurl=' + linkvar+'&type='+ajaxTarget,true);//asynchron
	resObjekt.open('get','typo3conf/ext/tut_unobtrusiveajax/media/parserscript.php?linkurl=' + linkvar,true);//asynchron
	resObjekt.onreadystatechange = handleResponse;
	resObjekt.send(null);
}

function handleResponse() {
	if(resObjekt.readyState == 4){
		var response=resObjekt.responseText;
		var stringArrayContent = response.split('xxSPLITRESPONSEHERExx');
		var responseContent = stringArrayContent[0];
		var responseTitle = stringArrayContent[1];
		//alert(ajaxTarget+ " " + $('content'+ajaxTarget));
		$('content'+ajaxTarget).innerHTML =responseContent;
		document.title=responseTitle;
		// replace links for the new window
		if(ajaxTarget==1) {
			// first window
			getElementsByClassNameAndReplace("ajaxLink1");
			// show gallery (calls same stuff as from domready)
			/*
			if ($('MooFlow')) {
				$$('.MooFlowieze').each(function(mooflow){
					new MooFlow(mooflow);
				});
				myMooFlowPage.start();
			}
			*/
		} else if (ajaxTarget==2) {
			// second window
			getElementsByClassNameAndReplace("ajaxLink2");
		}
		
		// third window does not contain navigation

		// reinit shadowbox
		// documentation of api: http://www.influenza.unam.mx/shadowbox/doc/api.html
		if (!window.ie) {
			Shadowbox.clearCache();
		} 
		Shadowbox.init({ skipSetup: true });
		Shadowbox.setup(); 
	}
}

window.addEvent('domready', function(){
	startSwAjax();
});
/** END Change partial page content with Ajax **/ 

