// JavaScript Document

//common Display functions
{

	/* Mootools 1.11 evalScripts option bug fix by Arkebion
	   added support for style tags coming in response */
	/* After upgrading to mootools 1.2 this part is closed by ergün */

	var Ajax = Ajax.extend({

		evalScripts: function(){
			var script, scripts, style, styles;
			if (this.options.evalResponse || (/(ecma|java)script/).test(this.getHeader('Content-type'))) scripts = this.response.text;
			else {
				scripts = [];
				var regexp = /<script[^>]*>([\s\S]*?)<\/script>/gi;
				while ((script = regexp.exec(this.response.text))) scripts.push(script[1]);
				scripts = scripts.join('\n');
			}
			if (scripts) (window.execScript) ? window.execScript(scripts) : window.setTimeout(scripts, 0);

			if (this.options.evalResponse || (/(ecma|java)style/).test(this.getHeader('Content-type'))) styles = this.response.text;
			else {
				styles = [];
				var regexp = /<style[^>]*>([\s\S]*?)<\/style>/gi;
				while ((style = regexp.exec(this.response.text))) styles.push(style[1]);
				styles = styles.join('\n');
			}
			if (styles)
			{
				var styleTag = document.createElement('style');
				styleTag.setAttribute('type', 'text/css');

				if (styleTag.styleSheet)
				{
					// IE
				    styleTag.styleSheet.cssText = styles;
				}
				else
				{
				// the world
				    var textNode = document.createTextNode(styles);
				    styleTag.appendChild(textNode);
				}
				var headTag = document.getElementsByTagName('head')[0];
				//headTag.removeChild(headTag.lastChild);
				headTag.appendChild(styleTag);
			}
		}

	});

	Element.extend({

		getForm: function ()
		{
			if($(this.parentNode).getTag() == "form")
				return $(this.parentNode);
			else
				return $(this.parentNode).getForm();
		}

	});

	// mootools1.1 https fix
/*
	Element.Events.domready.add = function(fn){
		if (window.loaded){
			fn.call(this);
			return;
		}
		var domReady = function(){
			if (window.loaded) return;
			window.loaded = true;
			window.timer = $clear(window.timer);
			this.fireEvent('domready');
		}.bind(this);
		if (document.readyState && window.webkit){
			window.timer = function(){
				if (['loaded','complete'].contains(document.readyState)) domReady();
			}.periodical(50);
		} else if (document.readyState && window.ie){
			if (!$('ie_ready')){
				var src = (window.location.protocol == 'https:') ? '/modules/layout/js/empty.js' : 'javascript:void(0)';
				document.write('<script id="ie_ready" defer src="' + src + '"><\/script>');
				$('ie_ready').onreadystatechange = function(){
					if (this.readyState == 'complete') domReady();
				};
			}
		} else {
			window.addListener("load", domReady);
			document.addListener("DOMContentLoaded", domReady);
		}
	};
*/
	function buttonToggler(obj)
	{
		if(obj.tagName == "IMG")
			obj.src = (obj.src.indexOf('H.png') == -1) ? obj.src.replace(/\.png/g, "H.png") : obj.src.replace(/\H.png/g, ".png");
		if(obj.tagName == "DIV")
		{
			obj.className = (!obj.className.match('Hover')) ? obj.className += "Hover" : obj.className.replace(/\Hover/g, "");
		}
	}

	function showToolTip(obj, content, widthPx, heightPx)
	{
		// set content
		$('balloonContent').set('html',content);

		// set width , height
		if(widthPx == undefined)
			widthPx = 146;
		if(heightPx != undefined)
		{
			$('balloonContainer').setStyle('height', heightPx + 'px');
			$('balloonMidRow').setStyle('height', (heightPx-82) + 'px');
		}

		$('balloonContent').setStyle('width', widthPx+'px');
		$('balloonContainer').setStyle('width', ($('balloonContent').offsetWidth+16) + 'px');

		heightDiff = 102;
		if($('balloonContent').offsetHeight > 70)
		{
			if(heightPx == undefined)
			{
				$('balloonMidRow').setStyle('height', ($('balloonContent').offsetHeight-40) + 'px');
				heightDiff = $('balloonContent').offsetHeight+32;
			}
			else
			{
				heightDiff = $('balloonContainer').offsetHeight-10;
			}
		}
		else
		{
			$('balloonMidRow').setStyle('height', '35px');
		}

		// position the balloon
		$('balloonContainer').setStyle('top', (obj.getPosition().y - heightDiff) + 'px'); // -$('balloonTip1').offsetHeight
		$('balloonContainer').setStyle('left', obj.getPosition().x + 'px');

		// display it
		$('balloonContainer').setStyle('visibility', 'visible');
		$('balloonContent').setStyle('visibility', 'visible');
		$('balloonContainer').setAttribute('openerObj', content);
	}

	function hideToolTip()
	{
		$('balloonContent').setStyle('visibility','hidden');
		$('balloonContainer').setStyle('visibility','hidden');
		$('balloonContainer').setAttribute('openerObj', '');
	}

	function toolTipToggler(obj, content, widthPx, heightPx)
	{
		if($('balloonContainer').getStyle('visibility') == 'hidden')
		{
			showToolTip(obj, content, widthPx, heightPx);
		}
		else
		{
			if($('balloonContainer').getAttribute('openerObj') == content)
				hideToolTip();
			else
				showToolTip(obj, content, widthPx, heightPx);
		}
	}

	var collapsibles = new Array();
	function initDisplayEffects(element)
	{
		//list of target elements

		var list = (element != null) ? $$("#"+element+" .collapsible") : $$('.collapsible');
		//list elements to be clicked on
		var headings = (element != null) ? $$("#"+element+" .toggler") : $$('.toggler');

		//array to store all of the collapsibles
		collapsibles = new Array();

		topUserMenuExists = false;
		headings.each( function(heading, i)
		{
			//for each element create a slide effect
			var collapsible = new Fx.Slide(list[i],
			{
				duration: 300,
				transition: Fx.Transitions.linear,
				onComplete: function() { if(heading.getProperty('onComplete') != undefined && heading.getProperty('onComplete').length) aaa=eval(heading.getProperty('onComplete')); },
				onStart: function() { if(heading.getProperty('onStart') != undefined && heading.getProperty('onStart').length) aaa=eval(heading.getProperty('onStart')); }
			});
			//and store it in the array
			heading.setProperty('collapsibleIndex', i);
			collapsibles[i] = collapsible;

			//add event listener
			heading.removeEvent('click');
			heading.addEvent('click', function(e)
			{
				list[i].setStyle('display','block');
				list[i].setProperty('collapsibleIndex', i);
				collapsible.toggle();
				if(heading.hasClass("question"))
				{
					if(heading.style.fontWeight == 'bold')
						heading.setStyle("font-weight","normal");
					else
						heading.setStyle("font-weight","bold");
				}
				return true;
			});

			if(heading.getAttribute('hide'))
				collapsible.hide();

			//collapse all of the list items
			//collapsible.hide();
		});

		//list elements to be clicked on
		var accordionHeadings = (element != null) ? $$("#"+element+" .accordionToggler") : $$('.accordionToggler');
		//list elements to be opened
		var accordionList = (element != null) ? $$("#"+element+" .accordionCollapsible") : $$('.accordionCollapsible');

		//for each element create a slide effect
		var myAccordion = new Accordion(accordionHeadings, accordionList, {
			opacity : false,
	    	onComplete: function()
	    	{
	        	//this.display.delay(2500, this, (this.previous + 1) % this.togglers.length);
	    	}
		});

		enableTooltips();
	}

}
// utility
{
	function ajaxifyFormsLinks(element)
	{
		var list = (element != undefined) ? $$("#"+element+" .ajaxForm") : $$('.ajaxForm');
		list.each( function(form) {
			form.removeEvents('submit');
			form.addEvent('submit', function(e) {

				new Event(e).stop();
				var isValid = validate(this);
				if(!isValid) return false;

				if(this.getProperty('beforeSubmit'))
				{
					isValid = eval(this.getProperty('beforeSubmit'));
					if(!isValid) return false;
				}

				if(!this.getProperty('action').match('layout=empty'))
				{
					this.setProperty('action', this.getProperty('action')+'&layout=empty');
				}

				if(isValid)
				{

					if(this.getProperty('donteval'))
						evalStatus = false;
					else
						evalStatus = true;

					if(this.getProperty('method'))
						method_ = this.getProperty('method');
					else
						method_ = 'post';

					formTarget_ = this.getProperty('formTarget');

					// ajax load ile değiştir
					this.getElements('input.image').each(function(item_) {
						if(item_.src != '/img/ajaxLoadSmall.gif')
						{
							submitImageBuffer = item_.src;
							item_.src = '/img/ajaxLoadSmall.gif';
						}
					});
					//alert(2);
					if(this.getProperty('oncomplete'))
					{
						this.set('send', {
					        method: method_,
							evalResponse:evalStatus,
							evalScripts:true,
							onComplete:function(r){
								eval(form.getProperty('oncomplete')+'(r)');
								// ajax load ile yalllaa
								form.getElements('input.image').each(function(item_) {
									item_.src = submitImageBuffer;
								});
							}
					    });
					}
					else if(formTarget_)
					{
						//alert(1);
						this.set('send', {
				        	method: method_,
							evalResponse:evalStatus,
							evalScripts:true,
							onSuccess:function(html){
								$(formTarget_).set('text', '');
								$(formTarget_).set('html', '');
								$(formTarget_).set('html', html);
								postProcessPage( formTarget_ );
								// ajax load ile yalllaa
								form.getElements('input.image').each(function(item_) {
									item_.src = submitImageBuffer;
								});
							}
					    });
					}
					else
					{
						//alert(this.action);
						this.set('send', {
							method: method_,
							evalResponse: evalStatus,
							evalScripts: true,
							onComplete: function() {
								// ajax load ile yalllaa
								form.getElements('input.image').each(function(item_) {
									item_.src = submitImageBuffer;
								});
							}
						});
					}
					this.send();
				}
			});

		});
		var list = (element != null) ? $$("#"+element+" .ajaxLink") : $$('.ajaxLink');

		list.each( function(link) {
			link.removeEvent('click');
			link.addEvent('click', function(e) {
				e = new Event(e).stop();

				if(link.getProperty('confirm'))
					var flag = confirm(link.getProperty('confirm'));
				else
					var flag = true;

				if(flag)
				{
					$(link.getProperty('linkTarget')).set("html","<img src='/img/ajaxLoad.gif' width='32' height='32' alt='yukleniyor'/>");

					var url = link.href+"&layout=empty";
					var linkTarget = link.getProperty('linkTarget');

					new Ajax(url, {
						method: 'get',
						evalScripts:true,
						onSuccess:function(html){
							$(linkTarget).set('text', '');
							$(linkTarget).set('html', '');
							$(linkTarget).set('html', html);
							postProcessPage(linkTarget);
							//var scroller = new Fx.Scroll(window).toElement(linkTarget);
							if( ($(linkTarget).getPosition().y > (document.getScroll().y+window.getHeight())) || ($(linkTarget).getPosition().y < document.getScroll().y))
							{
								var scroller = new Fx.Scroll(window).toElement(linkTarget);
							}
						}
					}).request();
					/* for moo 1.2 EK
					var request = new Request({
						url: url_,
						evalScripts:true,
						onSuccess:function(responseText, responseXML){
							$(linkTarget).set('text', '');
							$(linkTarget).set('html', '');
							$(linkTarget).set('html', responseText);
							postProcessPage(linkTarget);
							var scroller = new Fx.Scroll(window).toElement(linkTarget);
						}
					}).send();
					*/
				}
			});
		});

	}
	function ajaxifyLinksWithEfect(element)
	{
		var list = (element != null) ? $$("#"+element+" .ajaxLinkWithEfect") : $$('.ajaxLinkWithEfect');
		var linkFx = [];
		list.each( function(link,i) {
			link.removeEvent('click');
			link.addEvent('click', function(e) {
				e = new Event(e).stop();
				linkFx[i] = new Fx.Morph(link.getProperty('linkTarget'), {duration:350, wait:false});

				linkFx[i].start({
				    'opacity': [1,0]
				}).chain(function()
				{
					var url = link.href+"&layout=empty";
					new Ajax(url, {
							method: 'get',
							update: link.getProperty('linkTarget'),
							evalScripts:true,
							onComplete:function(){

								//removed "postProcessPage" if you want effects make the requested page simplifucked.
								linkFx[i].start({
								    'opacity': [0,1]
								});
						}
					}).request();
				});
			});
		});


	}

	//screen blocker
	var mooWindow     = null;
	var screenBlocker = null;
	var popupFx 	  = null;

	function boxifyLinks(element)
	{
		var boxedLinks = (element != null) ? $$("#"+element+" .boxed") : $$('.boxed');

		boxedLinks.each(function (linkbox){
			linkbox.removeEvent('click');
			linkbox.addEvent("click",function (e){
				e = new Event(e).stop();
				_blockScr(true);
				popupFx = new Fx.Morph($("popupWindow"), {duration:200, wait:false});
				$("popupWindow").setStyles({
					position: 'absolute',
					display : 'block',
					zIndex: '55557'
				});
				$("bufferIframe").src = linkbox.href;

			});

		});

	}
	// Hide element
	function hide( el ){ el.style.display='none'; }
	// Show element
	function show( el ){ el.style.display='block'; }
	// Toggle element display
	function toggleDisplay( el ){ el.style.display = (el.style.display=='none' ? '' : 'none'); }

	function postProcessPage(element)
	{
		initDisplayEffects(element);
		ajaxifyFormsLinks(element);
		boxifyLinks(element);
		ajaxifyLinksWithEfect(element);
		if(pageType == 'full' && !element)
		{
			pagerHoverer();
			//animateBasket();
		}
		// autocomplete leri tanı
		$$('input.inputAutocomplete').each(function(item, index)
		{
			makeAC(item, item.getProperty('url'));
		});
	}

	function pagerHoverer(element)
	{
	//list of target elements

		var list = (element != null) ? $$("#"+element+" .page") : $$('.page');
		//list elements to be clicked on


		list.each( function(pageItem) {
			pageItem.addEvent("mouseenter", function(e){
				buttonToggler(pageItem);
			});
			pageItem.addEvent("mouseleave", function(e){
				buttonToggler(pageItem);
			});

		});
	}

	function itemHoverer(element)
	{
	//list of target elements

		var list = (element != null) ? $$("#"+element+" .item") : $$('.item');
		//list elements to be clicked on


		list.each( function(pageItem) {
			pageItem.addEvent("mouseenter", function(e){
				buttonToggler(pageItem);
			});
			pageItem.addEvent("mouseleave", function(e){
				buttonToggler(pageItem);
			});

		});
	}

	/* lightbox */
	function resizeBlocker()
	{
		if(screenBlocker)
		{
			screenBlocker.setStyle("width",document.documentElement.offsetWidth+10);
			screenBlocker.setStyle("height",document.documentElement.offsetHeight+10);
		}
	}

	function _blockScr( block )
	{
		if( block )
		{
			document.documentElement.style.overflow = 'hidden';
			_documentBlocked = true;
			$('_scrBlock').style.display = '';
			$('_scrBlock').setStyle("width", window.getWidth()+"px");
			$('_scrBlock').setStyle("height" , window.getHeight()+10+"px");
			//$('_scrBlock').setOpacity(0.1);
		}
		else
		{
			_documentBlocked = false;
			document.body.style.overflow = '';
			document.documentElement.style.overflow = '';
			$('_scrBlock').style.width = $('_scrBlock').style.height = '0px';
			hide( $('_scrBlock') );
		}
	}

	function openLightBox(targetUrl, width, height)
	{

		_blockScr(true);
		midHeight = height-71;
		$("lbLoading").setStyle("display","block");
		left_ = ((window.getWidth()-width) / 2)+window.getScrollLeft();
		top_ = ((window.getHeight()-height) / 2)+window.getScrollTop();

		$('lbMainContainer').setStyle('top', top_+'px');
		$('lbMainContainer').setStyle('left', left_+'px');
		$('lbMainContainer').style.width = width+'px';
		$('lbMainContainer').style.height = height+'px';
		$('lbMainContainer').style.display = '';

		$('lbTopMid').style.width = (width-40)+'px';


		$('lbMidContainer').setStyle('height', midHeight+'px');
		$('lbMidContainer').setStyle('width', width+'px');

		$('lbContentIframe').setStyle('width', (width-40)+'px');
		$('lbContentIframe').setStyle('height', (midHeight)+'px');

		$('lbLoading').setStyle('width', (width-40)+'px');
		$('lbLoading').setStyle('height', (midHeight-60)+'px');

		$('lbBottomMid').style.width = (width-40)+'px';

		$('_scrBlock').setStyle("top",window.getScrollTop());
		$("lbContentIframe").src = targetUrl;

	}
	function resizeLightBox(width, height)
	{
		midHeight = height-71;
		left_ = ((window.getWidth()-width) / 2)+window.getScrollLeft();
		top_ = ((window.getHeight()-height) / 2)+window.getScrollTop();

		$('lbMainContainer').setStyle('top', top_+'px');
		$('lbMainContainer').setStyle('left', left_+'px');
		$('lbMainContainer').style.width = width+'px';
		$('lbMainContainer').style.height = height+'px';
		$('lbMainContainer').style.display = '';

		$('lbTopMid').style.width = (width-40)+'px';

		$('lbMidContainer').setStyle('height', midHeight+'px');
		$('lbMidContainer').setStyle('width', width+'px');

		$('lbContentIframe').setStyle('width', (width-40)+'px');
		$('lbContentIframe').setStyle('height', (midHeight)+'px');

		$('lbBottomMid').style.width = (width-40)+'px';

		$('_scrBlock').setStyle("top",window.getScrollTop());
	}
	function closeLightBox()
	{
		$('lbContentIframe').src = "/img/ajaxLoad.gif";
		$('lbMainContainer').setStyle("display","none");
		_blockScr(false);
		$('lbTopText').set("html","Yükleniyor...");
	}
	/* lightbox end */

	/*
	verilen url'e o ana kadar girilen değerleri
	"value" form field ı submit edilmiş gibi gönderir
	*/
	var completer = [];
	function makeAC(inputObj, contentURL)
	{
		var contentURL = contentURL+"&layout=empty";
		completer[$(inputObj).getProperty("name")] = new Autocompleter.Ajax.Xhtml(
		//completer[$(inputObj).getProperty("name")] = new Autocompleter.Request.HTML(
			inputObj,
			contentURL,
			{
				'onSelection': function(el, selected_, value_, input_) {
					// ürün karşılaştırma için eklendi EK
					//alert(selected_ + ' - ' + value_ + ' - ' + input_);
					elementName = inputObj.getProperty('name')+'Id';
					if($(elementName))
					{
						$(elementName).value = selected_.getAttribute('value');
					}
				},

				'injectChoice': function(choice) {
					// choice is one <li> element
					var text = choice.getFirst().getNext();
					//var text = choice.getFirst();

					// the first element in this <li> is the <span> with the text
					var value = text.getText();
					// inputValue saves value of the element for later selection
					choice.inputValue = value;
					// overrides the html with the marked query value (wrapped in a <span>)
					//text.set('html', this.markQueryValue(value));
					// add the mouse events to the <li> element
					this.addChoiceEvents(choice);
				},


				'postData': {html: 1}
			});
	}

	function searchByProperty(propertyId, propertyName, propertyValue)
	{
		$('keywords').value = 'ozellikNo:'+propertyId+' ozellik:'+propertyName+' deger:'+propertyValue;
		$('searchFormTop').submit();
	}

	function isNumber(evnt,obj)
	{
		var nn=obj.value
		var charCode = (navigator.appName == "Netscape") ? evnt.which : evnt.keyCode
		if (obj.value.length==0 && charCode==45) return true

		if (nn.indexOf(".") != -1 && obj.value.length > (nn.indexOf(".")+2) && charCode != 8 && charCode != 39 && charCode != 37)
			return false;
		if (charCode==46 && nn.indexOf(".")==-1) return true
		if (charCode == 44 && nn.indexOf(".")==-1)
		{
			obj.value = obj.value + ".";
			return false;
		}

		if (charCode > 31 && (charCode < 48 || charCode > 57 ) && !(charCode <= 105 && charCode >= 96 ) && (charCode != 36) && (charCode != 35) && (charCode != 46) && (charCode != 37) && (charCode != 39 && (charCode != 110) && (charCode != 190))){
		    return false
		}
		return true
	}

	function searchValidate(form_, value_)
	{
		if(value_.trim().length < 3)
		{
			alert('Arama Kriteriniz En Az 3 Karakter olmalıdır!');
			return false;
		}

		return true;
	}

	function countChars(item_)
	{
		charLimit = 1000;
		charCounted = item_.value.length;
		if(charCounted > charLimit)
		{
			item_.value = item_.value.substring(0, charLimit-1);
			charCounted = charLimit-1;
		}
		$('charCount').set('text',charCounted+'/'+charLimit);
	}

	function showError(errorMessageContainer, errorMessage)
	{
		$(errorMessageContainer).set('html',errorMessage);
		$(errorMessageContainer).effect('opacity', {duration: 0}).set(1);
		$(errorMessageContainer).effect('opacity', {duration: 2000 }).start(1,0);
	}

	function openUpdProductFollowUp(id)
	{
		openLightBox('/?a=customer.pfuUpdForm&layout=popup&productId='+id, 380, 260);
	}

	function openUpdForumFollowUp(forumSubjectId)
	{
		openLightBox('/?a=forum.followUpForm&layout=popup&forumSubjectId='+forumSubjectId, 380, 260);
	}

	function updateFeedBackTogglerText()
	{
		temp_collapsible = collapsibles[$('feedBackToggler').getProperty('collapsibleIndex')];
		if(!temp_collapsible.open)
		{
			$('feedBackTogglerArrow').src = '/img/arrowDownWhite.png';
			$('feedBackTogglerText').setText('Aç');
		}
		else
		{
			$('feedBackTogglerArrow').src = '/img/arrowUpWhite.png';
			$('feedBackTogglerText').setText('Kapa');
		}
	}


	//<![CDATA[

	window.addEvent('domready', function() {

		new SmoothScroll();
		mooWindow     = $(window);
		screenBlocker = $('_scrBlock');

		postProcessPage();

	});

	window.addEvent('resize', function() {
		if(pageType == 'full')
		{
			resizeBlocker();
		}
	});

	function setItemsPerPage(itemCount,container,url)
	{
		$(container).set("html","<img src='/img/ajaxLoad.gif' width='32' height='32' alt='yukleniyor'/>");

		var target = url+"&layout=empty&itemCount="+itemCount;

		new Ajax(target, {
			method: 'get',
			update: container,
			evalScripts:true,
			onComplete:function(){ postProcessPage(container) }
		}).request();
	}

	//]]>

	function odump(object, depth, max){
	  depth = depth || 0;
	  max = max || 2;

	  if (depth > max)
		return false;

	  var indent = "";
	  for (var i = 0; i < depth; i++)
		indent += "  ";

	  var output = "";
	  for (var key in object){
		output += "\n" + indent + key + ": ";
		switch (typeof object[key]){
		  case "object": output += odump(object[key], depth + 1, max); break;
		  case "function": output += "function"; break;
		  default: output += object[key]; break;
		}
	  }
	  return output;
	}

	function popUp(content)
	{

		var frog = window.open("","wildebeast","width=300,height=300,scrollbars=1,resizable=1")

		var html = "<html><head></head><body>"
		html += content
		html += "</body></html>"

		//variable name of window must be included for all three of the following methods so that
		//javascript knows not to write the string to this window, but instead to the new window

		frog.document.open()
		frog.document.write(html)
		frog.document.close()

	}
}
