var helper = {

	Version: '0.1',
	extKey: 'sfpHelper',

	hideElements : function (boxId, tagName) {

	    hideMe = new Array();
	    hideMe = $A($(boxId).getElementsByTagName(tagName)).each(function(e) {

		    if (e.style.visibility == '' || e.style.visibility == 'visible') {
			    e.style.visibility = 'hidden';
		    } else {
			    e.style.visibility = 'visible';
		    }

	    });
	},

	hideElementByClassName : function (container, className) {

		var overlaysOpen = document.getElementsByClassName(className,container);
		overlaysOpen.each(function(element) {
			element.setStyle ({
				display: 'none'
			})
		});

	},

	preloadImages : function(imglist) {
	    var imgs = new Array();
	    var count;
	    if (document.images) {
		for (count=0; count<imglist.length; count++) {
		    imgs[count]=new Image(); imgs[count].src=imglist[count];
		}
	    }
	},

	getUrlParams : function (url) {
		return url.split('?');
	},

	random : function(imgs) {
		var imgsNum = 0;
		imgs.each(function(imgs){
		    imgsNum ++
		});

		var imgSelect = Math.round(Math.random()*(imgsNum-1));
		var bgImage = imgs[imgSelect];

		var header = $('header');

		if(header) {
			header.setStyle({
			    backgroundImage: 'url('+bgImage+')'
			});
		}
	},

	mark : function(element,errorMsg,marked) {
		try{
		   var elm = $(element);
		    var eadvice = 'captcha-advice-required-' + element;
	    if(marked) {
		   advice = '<div class="validation-advice" id="'+ eadvice +'" style="display:none" >' + errorMsg + '</div>'
					    switch (elm.type.toLowerCase()) {
						    case 'checkbox':
						    case 'radio':
							    var p = elm.parentNode;
							    if(p) {
								    new Insertion.Bottom(p, advice);
							    } else {
								    new Insertion.After(elm, advice);
							    }
							    break;
						    default:
							    new Insertion.After(elm, advice);
					}
				    if(typeof Effect == 'undefined') {
					    $(eadvice).style.display = 'block';
				    } else {
					    new Effect.Appear($(eadvice), {duration : 1 });
				    }
			    elm.removeClassName('validation-passed');
			    elm.addClassName('validation-failed');
			    return false;
		    } else {
			    if($(eadvice) != null) $(eadvice).remove();
			    elm.removeClassName('validation-failed');
			    //elm.addClassName('validation-passed');
			    return true;
		    }
		    } catch(e) {
			    throw(e)
		    }
	    },


	//showloading
	loading : function (boxId, action) {

	    var ajaxLoader = $(boxId);

	    if (ajaxLoader) {

		 if (action == 'start') {
		    Effect.Appear (ajaxLoader);
		 } else {
		   ajaxLoader.hide();
		}

	    }
	},

	overlay : function (element,boxOverlay,boxParent,overlayClass) {

		//create a uniqe id
		var rId = this.uniqueId();

		if (boxOverlay.style.display == 'none') {

			boxOverlay.id = 'b'+rId;

			// creat a dynamic margin
			element.id = 'a'+rId;
			var aTagWidth = $('a'+rId).getWidth();

			boxOverlay.style.marginLeft = 20+aTagWidth+'px';

			helper.hideElementByClassName(boxParent,overlayClass);

			//close open overlayBoxes
			Effect.Appear(boxOverlay);

		}
	},

	//create a uniqe id
	uniqueId : function () {
		var d = new Date();
		var rId = Math.round(Math.random()*d);
		return rId;
	},

	cursor : function (element) {
		element.style.cursor='pointer';
	}
}

var image = {

	showOverlay : function (element) {

		var rId = helper.uniqueId();
		element.id = 'imgLi'+rId;

		image.hideOverlay(element);
		var ulImagList = element.parentNode;

		var currentImages = ulImagList.getElementsBySelector('img');
		var index = 0;

		/* Prepare thumbs */
		currentImages.each(function(e) {
			index ++;
			e.name = 'img'+index;
		});

		var currentImage = $('imgLi'+rId).getElementsBySelector('img')[0];

		/* Prepare overlays */
		if(ulImagList.next()) {

			var overlayImages = ulImagList.next().getElementsBySelector('img');
			index = 0;
			overlayImages.each(function(e) {
				index ++;
				e.name = 'img'+index;
			});


			/* Show overlay */
			overlayImages.each(function(overlayImage) {

				if (overlayImage.name == currentImage.name) {

					if(overlayImage.up().style.display == 'none') {

						overlayImage.up().style.display = 'block';
						var overlayHeight = overlayImage.up().getHeight();
						overlayImage.up().up().setStyle ({
							minHeight: overlayHeight+'px',
							height: overlayHeight+'px'
						});
					}
				}

			});
		}


	},

	hideOverlay : function (element) {

		var rId = helper.uniqueId();
		if (element) {
			var ulImagList = element.parentNode;
		}
		ulImagList.id = 'ulImg'+rId;

		if($('ulImg'+rId).next()) {
			var overlays = $('ulImg'+rId).next().getElementsBySelector('li');

			overlays.each(function(overlay) {

				if(overlay.style.display != 'none') {
					overlay.style.display = 'none';
				}
			});
		}

	},

	hideElement : function (element) {
		element.style.display = 'none';
		element.parentNode.setStyle ({
			minHeight: '',
			height: ''
		})
	}

}

var pluginTipAfriend = {

	Version: '0.2',
	baseUrlUpdate: 'index.php?id='+JSFE['pid']+'&L='+JSFE['sys_language_uid']+'&type=101&',
	box: 'tipAfriend',
	captchaMessage:  JSFE['form']['captchaWrong'],

	showForm : function (tipUrl) {

		//hide select boxes
		if (JSFE['browser']['name'] == 'Explorer' & JSFE['browser']['version'] < 7) {
			helper.hideElements('mainContent','select');
		}

		//show box
		Effect.Appear($('ajaxFocus'), {
			from: 0.0, to: 0.8
		});
		helper.loading('tipLoading','start');
		Element.show('tipAfriendContainer');

		//is it an event page (could be done smoother I think)
		try {
			var eventUid = JSFE['tx_sbvevents_pi1']['uid'];
		} catch(err) {

		}

		if(eventUid) var eventParams = '&tx_sbvevents_pi1[showUid]='+eventUid;

		var url = this.baseUrlUpdate+helper.getUrlParams(window.location.href)[1]+eventParams+'&ajaxupdate[extKey]=tipafriend&tipUrl='+encodeURIComponent(tipUrl);
		new Ajax.Updater(this.box, url, {
			method: 'get',
			onComplete: helper.loading('tipLoading','stop')
		});

	},

	submitForm : function (tipUrl,formVars) {

		$('buttonTipForm').disabled = true;
		Effect.Fade('tipForm');

		new Ajax.Updater(this.box, this.baseUrlUpdate+helper.getUrlParams(window.location.href)[1]+'&ajaxupdate[extKey]=tipafriend&sendTip=1&tipUrl='+tipUrl, {
			method: 'post',
			parameters: formVars,
			evalScripts: false,
			onComplete: doFollowing = function () {
			    //enableButton
			    var buttonTipForm = $('buttonTipForm');
			    if(buttonTipForm) {
				buttonTipForm.disabled = false;
			    }
			}
		});

	},

	validateCap : function (tipUrl,capString) {

		//disableButton
		var buttonTipForm = $('buttonTipForm');
		if(buttonTipForm) {
			buttonTipForm.disabled=true;
		}

		new Ajax.Request(this.baseUrlUpdate+'&ajaxupdate[extKey]=tipafriend&eID=tipfriend&&sendTip=1&captcha_response='+capString, {

		       method: 'get',
		       onSuccess: doFollowing = function(transport){
				//disableButton
				var buttonTipForm = $('buttonTipForm');

				if(buttonTipForm) {
				  buttonTipForm.disabled=false;
				}

				var response = transport.responseText.strip() || 'no response';

				if(response=="capt"){
				       helper.mark('tipFormCommentCaptcha',pluginTipAfriend.captchaMessage,false);
				       pluginTipAfriend.submitForm(tipUrl,Form.serialize('tipForm'));
			       } else {
				  helper.mark('tipFormCommentCaptcha',pluginTipAfriend.captchaMessage,true);
			       }
			}
	       });

	},

	validateForm : function (tipUrl) {

		//enableButton
		var ttipUrl = tipUrl;

		if(tipUrl=='undefined'||tipUrl==''){
		    ttipUrl = window.location.href;
		}

		helper.mark('tipFormCommentCaptcha','bla',false);
		valid = new Validation('tipForm', {onSubmit:false});
		var result = valid.validate();
		if(result == true){
		    this.validateCap(ttipUrl,$F('tipFormCommentCaptcha'));
		}

	},

	remove : function () {

		//$('ajaxFocus').style.display = 'none';
		Effect.Fade(('ajaxFocus'));
		$('tipAfriendContainer').style.display = 'none';

		if (JSFE['browser']['name'] == 'Explorer' & JSFE['browser']['version'] < 7) {
			helper.hideElements('mainContent','select');
		}
	}

}


var pluginSrfreecap = {

	newFreeCap : function () {

	    // loads new freeCap image
	    if(document.getElementById) {

		// extract image name from image source (i.e. cut off ?randomness)
		var theImage = $('tx_srfreecap_pi2_captcha_image');
		var parts = theImage.src.split("&");
		// add ?(random) to prevent browser/isp caching
		// parts[0] should be id=page_id
		// parts[1] should be L=sys_language_uid
		theImage.src = parts[0] + "&" + parts[1] + "&set=" + Math.round(Math.random()*100000);

	    } else {
		alert("Sorry, cannot autoreload new image\nSubmit the form and a new image will be loaded");
	    }
	}
}

var pluginSiteEditor = {

	showOverlay : function (element) {

		var overlayLink = $('tx_siteeditor_pi1_quick');
		var overlayLinkWidth = overlayLink.down().getWidth()+40;
		var overlayPositionRealOffset = Position.realOffset(overlayLink.down())[1];
		var overlayPositionPage = Position.page(overlayLink.down())[1];

		var overlay = $('tx_siteeditor_pi1');

		overlay.setStyle ({
			left: overlayLinkWidth+'px',
			top: overlayPositionPage+overlayPositionRealOffset-overlay.getHeight()+'px'
		});

		if(overlay.style.display == 'none') {
			Effect.Appear(overlay);
		}
	},

	closeOverlay : function () {

		var overlay = $('tx_siteeditor_pi1');
		if(overlay.style.display != 'none') {
			overlay.style.display = 'none';
		}

	}

}

/*
 - loading shadowbox 
 - label is set in dynamic js 
 - image is global
*/
function indexedSearchWin () {
	if(typeof Shadowbox != "undefined") {
		/* disable close function */
		Shadowbox.close=function(){return false;}
		Shadowbox.open({
			player:     'html',
			content:    '<div style="width:100%;height:100%;background:#fff;text-align:center;"><br /><br /><strong>' + JSFE['indexedsearch_preloadtext'] + '</strong><br /><img src="http://www.landwirtschaft.ch/typo3conf/ext/sfptemplate/files/global/images/ajaxLoader.gif"></div>',
			height:     200,
			width:      500,
			scrolling:  'no'
		},{
			overlayColor: '#ffffff',
			overlayOpacity: 0.8,
			scrolling:  'no'
		});
	}
}