/**
 * @author nik
 */
var groupview_start_view = true;
var my_description = "";
var my_path = '/fileadmin/products';
var single_product_view = my_path+'/single_product_view.html';
var myInSpeed	= 500;
var myWaitTime	= 5000;	/* ms */
var myMorphTime = 500;	/* ms */
var teaserStartHigh = 0;
var mainStartHigh = 0;
var distanzConstant = 30; //53;
var distanzConstantOutside = distanzConstant+25;// + 25;
var teaserParking = "";
var single_product_view_trys = 0;

// Request Variablen
var target;
//var internPath;
var requestParameter;
var myFullPathString;

/*
var req_start = new Request.HTML({
	url: single_product_view,
	method: 'get',
	encoding: 'utf-8',
	link: 'chain',
	async: 1,
    onSuccess: function(html){
        //Clear the text currently inside the results div.
        //$('teaser').set('text', '');
        $('teaser').adopt(html);
		//alert("req_start onSuccess : "+single_product_view);
        groupview_start_view = false;
    },
    //onFailure method which will let the user know what happened.
    onFailure: function(){
		single_product_view_trys++;
		alert ('The request failed for body. Try Nr.: '+single_product_view_trys);
		//$('teaser').set('text', 'The request failed for body.');
    }
});
*/

var req = new Request.HTML({
	url: '/typo3conf/ext/nao_tuerkiyem_products/pi1/return_single_view.php',
	method: 'get',
	encoding: 'utf-8',
//	async: 1,
//	'link': 'chain',
	onSuccess: function(responseTree, responseElements, responseHTML, responseJavaScript){
		//Clear the text currently inside the results div.
		//$('debugoutput').adopt(html); single_product_view_anim
		//alert('Success'+responseHTML+"  "+target);
		var myFirstElement = new Element('div', {id: 'myFirstElement'});
		myFirstElement.set('html', responseHTML);
		myFirstElement.inject(target);
		prepareShowCertificate();
		//target.adopt(myFirstElement);
		//target.adopt(responseHTML);
		//target.wraps(responseTree);
		//var temp = target.clone().get('html');
		//target.set('html', temp + responseHTML);
		//responseText.inject(target);
	},
	onComplete: function(){
		//alert('Complete');
	},
	//onFailure method which will let the user know what happened.
	onFailure: function(){
		//alert('ALERT !'+" "+my_path+my_description);
		single_product_view_trys++;
		alert ('The request failed for content. Try Nr.: '+single_product_view_trys);
	}
});



function InsertMyRequest(path){
	//alert(my_path+path);
	//internPath = path[0];
	requestParameter = path[1] + "&requestform=JSONRequest";
	//myFullPathString = internPath+"?"+requestParameter;
	//alert(myFullPathString);
	
	/*
	var req_insert = new Request.HTML({
        url: internPath,
		method: 'get',
		encoding: 'utf-8',
		//async: 1,
		//link: 'chain',
        onSuccess: function(html){
            //Clear the text currently inside the results div.
            //alert('OK !'+" "+my_path+my_description);
            //alert('disapiered!');
            //alert(html);
            //$('debugoutput').adopt(html);
			target.adopt(html);
            //html.inject($('single_product_view'))
			//var debug_target = $('debugoutput');
            //var_dump(html, debug_target, 10);
        },
        //onFailure method which will let the user know what happened.
        onFailure: function(){
            //alert('ALERT !'+" "+my_path+my_description);
			single_product_view_trys++;
			alert ('The request failed for content. Try Nr.: '+single_product_view_trys);
        }
    });
	*/
    // Object (noch unsichtbar) einfügen
    //alert(path[1]+"&requestform=JSONRequest");
	target = $('single_product_view');
	//target = $('debugoutput');
	target.set('text', '');
	//alert('now send!');
	req.send(requestParameter).chain(function(){
        // Die Höhe des eingesetzten Objects ermitteln.
        var ObjectSize		= $('single_product_view_body').getSize();
        var MainObjectSize	= $('main').getSize();
		//alert("The element is "+ObjectSize.x+" pixels wide and "+ObjectSize.y+"pixels high.");
		//alert("The element is "+MainObjectSize.x+" pixels wide and "+MainObjectSize.y+"pixels high.");
		$('close_single_product_view').addEvent('click', function(){
            closeView();
        });
        var myEffect_mainContent = new Fx.Morph('main', {
            duration: myInSpeed * 2, /* myInSpeed, */
            transition: Fx.Transitions.Sine.easeIn
        });
        var myEffect_blue = new Fx.Morph('single_product_view', {
            duration: myInSpeed,
            transition: Fx.Transitions.Sine.easeIn
        });
        var myEffect_anim = new Fx.Morph('single_product_view_anim', {
            duration: myInSpeed / 2,
            transition: Fx.Transitions.Sine.easeIn
        });
        var myEffect_teaser = new Fx.Morph('teaser', {
            duration: myInSpeed,
            transition: Fx.Transitions.Sine.easeIn
        });
        myEffect_mainContent.start({
            'height': 0
        });
        myEffect_teaser.start({
            'height': (ObjectSize.y + distanzConstantOutside)
        });
        myEffect_blue.start({
            'height': (ObjectSize.y + distanzConstantOutside) //Morphs the height from the current to 100px.   			'opacity': [0,1]   //Morphs the width from the current to 300px.
        })
        myEffect_anim.start({
            'height': (ObjectSize.y + distanzConstant), //Morphs the height from the current to 100px.
            'opacity': [0, 1] //Morphs the width from the current to 300px.
        });
    });
	return this;
}

/*
 var req_insert = new Request.HTML({url:my_path+my_description,
 onSuccess: function(html) {
 //Clear the text currently inside the results div.
 alert('OK !'+" "+my_path+my_description);
 $('single_product_view').set('text', '');
 //alert('disapiered!');
 $('single_product_view').adopt(html)
 },
 //onFailure method which will let the user know what happened.
 onFailure: function() {
 alert('ALERT !'+" "+my_path+my_description);
 $('single_product_view').set('text', 'The request failed.');
 }
 })
 */

var blendInElement = function (ElementToBlendIn, Duration) {
	var theTeaserEffect = new Fx.Morph(ElementToBlendIn, {
		duration: Duration,
		transition: Fx.Transitions.linear
	});
	theTeaserEffect.start({
		'opacity': [0, 1]
	})
}

var cycleReclam = function(){
    var MyReclamElements = $$('div.dimm_box_newProduct');
    MyReclamElements.each(function(el){
        var MyReclamElementEffect = new Fx.Morph(el.getElement('div.dimm_box_newProduct_02'), {
            duration: myMorphTime,
            transition: Fx.Transitions.linear
        });
        MyReclamElementEffect.start({
            'opacity': [0, 1],
            'height': [0, 179]
        }).chain(function(){
            // executes 5 seconds after completion of above effect
            this.start.delay(myWaitTime, this, {
                'opacity': [1, 0],
                'height': [179, 0]
            });
        });
    });
}

window.addEvent('load', function(){

	if ($('uid62')) {
		
		/*
		 * Slimbox Popup 
		 */
/*
		Slimbox.open(
			"/fileadmin/certificates/INFO-500x700.jpg",
			"Info",
			{
				overlayOpacity: 0.6,
				resizeTransition: Fx.Transitions.Elastic.easeOut,
				captionAnimationDuration: 0,
				counterText: "Image {x} sur {y}",
				closeKeys: [27, 70],
				nextKeys: [39, 83]
			}
		);

*/	}
	

	// Teaser Einblenden
	blendInElement($('nav'), 0);
	blendInElement($('teaser'), 1000);

	// Werbung ein und ausblenden
    var periodical;
    // Check if there is an Element for Reclam
    var MyReclamElements = $$('div.dimm_box_newProduct');
    if (MyReclamElements != 0) {
        cycleReclam();
        periodical = cycleReclam.periodical(myWaitTime * 2);
    }
});

window.addEvent('domready', function(){
	//Slimbox.scanPage;


	
    var myInSpeed = 500;
	//teaserParking = $('teaser').getFirst('div.tx-tgrstatichtml-pi1').clone();
    
    $$('#product_list a.single_product_details_link').addEvent('click', function(el){
        el.stop();
		//alert(this.get('href'));
		my_description = this.get('href');
		my_description = my_description.split ("?");
		my_description[1] = my_description[1].replace(/&/i, "&");
		//alert("Vor!");
		if (groupview_start_view) {
			//alert(my_description[1]);
            // getBody=1
			target = $('teaser');
			//internPath = my_description[0];
			teaserStartHigh = $('teaser').getSize().y;
			mainStartHigh	= $('main').getSize().y;
			//alert('Hier! '+teaserStartHigh);
			req.send('getBody=1').chain(function(){
				//alert("Reqest Start finished!");
				var myEffect_Teaser = new Fx.Morph($('teaser').getFirst('div.tx-tgrstatichtml-pi1'), {
					duration: myInSpeed,
					transition: Fx.Transitions.Sine.easeIn
				});
				var myEffect_blue = new Fx.Morph('single_product_view', {
					duration: myInSpeed,
					transition: Fx.Transitions.Sine.easeIn
				});
				groupview_start_view = false;
				myEffect_Teaser.start({
					'opacity': [1, 0]
				});
				myEffect_blue.start({
					'opacity': [0, 1]
				}).chain(function(){
					//alert(my_description);
					InsertMyRequest(my_description);
				});
			});
        }
        else {
            var myEffect_anim = new Fx.Morph('single_product_view_anim', {
                duration: myInSpeed,
                transition: Fx.Transitions.Sine.easeIn
            });
            myEffect_anim.start({
                'height': 0, //Morphs the height from the current to 100px.
                'opacity': [1, 0] //Morphs the width from the current to 300px.
            }).chain(function(){
                InsertMyRequest(my_description);
            });
        }
    });

	prepareShowCertificate();

    
    /*
     * The Request to get the Data Array to edit
     */
    /*	
     var jsonRequest = new Request.JSON({
     url: myRequestURL,
     onComplete: function(jsonObj) {
     }
     }).post(transformRequestArrayToJSON(myDataRequest));/*.chain(function(){
     alert(myData.data_To_Edit.ersterEintag);
     });*/
    /*
     * Test Button for development.
     */
    /*
     $('doIt').addEvent('click', function(e) {
     e.stop();
     //neuBuildButtons();
     myDataRequest = {
     'request'		: 'moredata',
     'request_info'	: {
     'urlToData'		: urlToData,
     }
     };
     var jsonRequest = new Request.JSON({
     url: myRequestURL,
     onComplete: function(jsonObj) {
     //var_dump (jsonObj, myDebugMe, 10);
     }
     }).post(transformRequestArrayToJSON(myDataRequest));
     // Var dump some Data!
     //var_dump (Cookie.read('clipboardElement'), myDebugMe, 10);
     
     }); */
});

function showCertifacteFunction () {
	Slimbox.open(
		"/fileadmin/certificates/halal_cert_5255091-335x468.jpg",
		"Halal Certificate 5255 2009",
		{
			overlayOpacity:				0.6,
			resizeTransition:			Fx.Transitions.Elastic.easeOut,
			captionAnimationDuration:	0,
			counterText:				"Image {x} sur {y}",
			closeKeys:					[27, 70],
			nextKeys:					[39, 83]
		}
	);
	//alert("show Zertificat");
}

function prepareShowCertificate() {
	var myCertificatElements = ([
		$('HEAD_FERTIG_HANCHEN_de_17'),
		$('HEAD_FERTIG_HANCHEN_tr_17'),
		$('HEAD_FERTIG_RIND_de_17'),
		$('HEAD_FERTIG_RIND_tr_17'),
		$('details_view_qualtitaet'),
		$('NEAD_NUGGET_NEU_de_89'),
		$('NEAD_NUGGET_NEU_tr_89'),
		$('HEAD_SCHNITZEL_NEU_de_89'),
		$('HEAD_SCHNITZEL_NEU_tr_89')
	]);

	myCertificatElements.each(function(showCertificat){
		if (showCertificat != null) {
			showCertificat.setStyle("cursor", "pointer");
			showCertificat.addEvent('click', function(e){
				//e.stop();
				showCertifacteFunction ();
			});
		}
	});
}

function closeView(){
	var teaser = $('teaser');
	var myEffect_Teaser_Background = new Fx.Morph(teaser.getFirst('div.tx-tgrstatichtml-pi1'), {
		duration: myInSpeed,
		transition: Fx.Transitions.Sine.easeIn
	});
    var myEffect_mainContent = new Fx.Morph('main', {
        duration: myInSpeed * 2, /* myInSpeed, */
        transition: Fx.Transitions.Sine.easeIn
    });
	//teaserParking.clone().inject(teaser);
	var myEffect_blue = new Fx.Morph('single_product_view', {
        duration: myInSpeed,
        transition: Fx.Transitions.Sine.easeIn
    });
    var myEffect_teaser = new Fx.Morph('teaser', {
        duration: myInSpeed * 2,
        transition: Fx.Transitions.Sine.easeIn
    });
    myEffect_mainContent.start({
        'height': mainStartHigh
    });
    myEffect_blue.start({
        'height': 0, //Morphs the height from the current to 100px.
        'opacity': [1, 0] //Morphs the width from the current to 300px.
    }).chain(function(){
        $('single_product_view').dispose();
    });
    myEffect_teaser.start({
        'height': teaserStartHigh
    });
	myEffect_Teaser_Background.start({
		'opacity': [0, 1]
	});
    
    groupview_start_view = true;
	target = $('teaser');
}

function call_listed_page(){
}

/*
 * var_dump
 */
function var_dump(variable, target, maxDeep) {
    target.set('html', "<pre></pre>");
    target.getElement('pre').set('text', varDump(variable, maxDeep));
}

function varDump(variable, maxDeep){
    var deep = 0;
    var maxDeep = maxDeep || 5;
    
    function fetch(object, parent){
        var buffer = '';
        deep++;
        
        for (var i in object) {
            if (parent) {
                objectPath = parent + '.' + i;
            }
            else {
                objectPath = i;
            }
            
            buffer += objectPath + ' (' + typeof object[i] + ')';
            
            if (typeof object[i] == 'object') {
                buffer += "\n";
                if (deep < maxDeep) {
                    buffer += fetch(object[i], objectPath);
                }
            }
            else 
                if (typeof object[i] == 'function') {
                    buffer += "\n";
                }
                else 
                    if (typeof object[i] == 'string') {
                        buffer += ': "' + object[i] + "\"\n";
                    }
                    else {
                        buffer += ': ' + object[i] + "\n";
                    }
        }
        
        deep--;
        return buffer;
    }
    
    if (typeof variable == 'object') {
        return fetch(variable);
    }
    
    return '(' + typeof variable + '): ' + variable + "\n";
}

/*
 * trasform Requestion Array to the JSon String.
 */
var transformRequestArrayToJSON = function(MyRequest){
    var myJSON = JSON.encode(MyRequest);
    var json = {
        'data': myJSON
    };
    return json;
};

/*
 * Update the Form, or output recived Error
 */
var updateForm = function(myDataRequest){
    var jsonRequest = new Request.JSON({
        url: myRequestURL,
        onComplete: function(jsonObj){
            if (jsonObj["errorStatus"]) {
                alert(jsonObj["text"]);
                //location.reload(false);
                location.href = document.URL;
            }
            else {
                //alert(myData.URL_to_Data);
                //location.reload(false);
                location.href = document.URL;
            }
        }
    }).post(transformRequestArrayToJSON(myDataRequest));
}




/*
	Slimbox v1.71 - The ultimate lightweight Lightbox clone
	(c) 2007-2009 Christophe Beyls <http://www.digitalia.be>
	MIT-style license.
*/
var Slimbox=(function(){var F=window,n=Browser.Engine.trident4,u,g,G=-1,o,w,E,v,y,M,s,m={},t=new Image(),K=new Image(),I,a,h,q,J,e,H,c,A,L,x,i,d,C;F.addEvent("domready",function(){$(document.body).adopt($$(I=new Element("div",{id:"lbOverlay",events:{click:D}}),a=new Element("div",{id:"lbCenter"}),H=new Element("div",{id:"lbBottomContainer"})).setStyle("display","none"));h=new Element("div",{id:"lbImage"}).injectInside(a).adopt(q=new Element("div",{styles:{position:"relative"}}).adopt(J=new Element("a",{id:"lbPrevLink",href:"#",events:{click:B}}),e=new Element("a",{id:"lbNextLink",href:"#",events:{click:f}})));c=new Element("div",{id:"lbBottom"}).injectInside(H).adopt(new Element("a",{id:"lbCloseLink",href:"#",events:{click:D}}),A=new Element("div",{id:"lbCaption"}),L=new Element("div",{id:"lbNumber"}),new Element("div",{styles:{clear:"both"}}))});function z(){var N=F.getScroll(),O=F.getSize();$$(a,H).setStyle("left",N.x+(O.x/2));if(v){I.setStyles({left:N.x,top:N.y,width:O.x,height:O.y})}}function l(N){["object",n?"select":"embed"].forEach(function(P){Array.forEach(document.getElementsByTagName(P),function(Q){if(N){Q._slimbox=Q.style.visibility}Q.style.visibility=N?"hidden":Q._slimbox})});I.style.display=N?"":"none";var O=N?"addEvent":"removeEvent";F[O]("scroll",z)[O]("resize",z);document[O]("keydown",p)}function p(O){var N=O.code;return u.closeKeys.contains(N)?D():u.nextKeys.contains(N)?f():u.previousKeys.contains(N)?B():false}function B(){return b(w)}function f(){return b(E)}function b(N){if(N>=0){G=N;o=g[N][0];w=(G||(u.loop?g.length:0))-1;E=((G+1)%g.length)||(u.loop?0:-1);r();a.className="lbLoading";m=new Image();m.onload=k;m.src=o}return false}function k(){a.className="";d.set(0);h.setStyles({backgroundImage:"url("+o+")",display:""});q.setStyle("width",m.width);$$(q,J,e).setStyle("height",m.height);A.set("html",g[G][1]||"");L.set("html",(((g.length>1)&&u.counterText)||"").replace(/{x}/,G+1).replace(/{y}/,g.length));if(w>=0){t.src=g[w][0]}if(E>=0){K.src=g[E][0]}M=h.offsetWidth;s=h.offsetHeight;var P=Math.max(0,y-(s/2)),N=0,O;if(a.offsetHeight!=s){N=i.start({height:s,top:P})}if(a.offsetWidth!=M){N=i.start({width:M,marginLeft:-M/2})}O=function(){H.setStyles({width:M,top:P+s,marginLeft:-M/2,visibility:"hidden",display:""});d.start(1)};if(N){i.chain(O)}else{O()}}function j(){if(w>=0){J.style.display=""}if(E>=0){e.style.display=""}C.set(-c.offsetHeight).start(0);H.style.visibility=""}function r(){m.onload=$empty;m.src=t.src=K.src=o;i.cancel();d.cancel();C.cancel();$$(J,e,h,H).setStyle("display","none")}function D(){if(G>=0){r();G=w=E=-1;a.style.display="none";x.cancel().chain(l).start(0)}return false}Element.implement({slimbox:function(N,O){$$(this).slimbox(N,O);return this}});Elements.implement({slimbox:function(N,Q,P){Q=Q||function(R){return[R.href,R.title]};P=P||function(){return true};var O=this;O.removeEvents("click").addEvent("click",function(){var R=O.filter(P,this);return Slimbox.open(R.map(Q),R.indexOf(this),N)});return O}});return{open:function(P,O,N){u=$extend({loop:false,overlayOpacity:0.8,overlayFadeDuration:400,resizeDuration:400,resizeTransition:false,initialWidth:250,initialHeight:250,imageFadeDuration:400,captionAnimationDuration:400,counterText:"Image {x} of {y}",closeKeys:[27,88,67],previousKeys:[37,80],nextKeys:[39,78]},N||{});x=new Fx.Tween(I,{property:"opacity",duration:u.overlayFadeDuration});i=new Fx.Morph(a,$extend({duration:u.resizeDuration,link:"chain"},u.resizeTransition?{transition:u.resizeTransition}:{}));d=new Fx.Tween(h,{property:"opacity",duration:u.imageFadeDuration,onComplete:j});C=new Fx.Tween(c,{property:"margin-top",duration:u.captionAnimationDuration});if(typeof P=="string"){P=[[P,O]];O=0}y=F.getScrollTop()+(F.getHeight()/2);M=u.initialWidth;s=u.initialHeight;a.setStyles({top:Math.max(0,y-(s/2)),width:M,height:s,marginLeft:-M/2,display:""});v=n||(I.currentStyle&&(I.currentStyle.position!="fixed"));if(v){I.style.position="absolute"}x.set(0).start(u.overlayOpacity);z();l(1);g=P;u.loop=u.loop&&(g.length>1);return b(O)}}})();

// AUTOLOAD CODE BLOCK (MAY BE CHANGED OR REMOVED)
Slimbox.scanPage = function() {
	$$("a").filter(function(el) {
		return el.rel && el.rel.test(/^lightbox/i);
	}).slimbox({}, null, function(el) {
		return (this == el) || ((this.rel.length > 8) && (this.rel == el.rel));
	});
};
if (!/android|iphone|ipod|series60|symbian|windows ce|blackberry/i.test(navigator.userAgent)) {
	window.addEvent("domready", Slimbox.scanPage);
}
