window.addEvent('domready', menuInitialize);

function menuInitialize() {
	$$('.l1menu .item').addEvents( {'mouseenter': menuOnMouse, 'mouseleave': menuOnMouse} );
}

function menuOnMouse(e) {
	var l2menu = this.getElement('.l2menu');

	if (l2menu) {
		l2menu.setStyle("visibility", (e.event.type == "mouseover") ? "visible" : "hidden");
	}
}

function newsrotatorSetup() {
  if (newsrotator.length) {
    rotatorpreload = new Array();
    nrtotal = newsrotator.length -1;
    rotatorpreload = new Image();
    nrcurrent = 0;
    nrnext = 1;
    $("newstitle").set("html",newstitles[nrcurrent]);
    $("newsabstract").set("html",newsabstracts[nrcurrent]);
    $("newslink").href = newslinks[nrcurrent];
    var currentli = "nrprev" + nrcurrent;
    $(currentli).className = "hover";
    $("next").src = newsrotator[nrcurrent];
    news_timeout = setTimeout("rotateNews()",5000);	
  }
	initialized = 1;
}

function swapImgs() {
	var myFx = new Fx.Tween("next", { duration:250,
		onComplete:function() {
			$("next").src = newsrotator[nrnext];
			var currentli = "nrprev" + nrcurrent;
			var nextli = "nrprev" + nrnext;
			$(currentli).className = "";
			$(nextli).className = "hover";
			$("newstitle").set("html",newstitles[nrnext]);
			$("newsabstract").set("html",newsabstracts[nrnext]);
			$("newslink").href = newslinks[nrnext];
			fadein("next",1);
			nrcurrent = nrnext;
		}
	}).start('opacity',1,0);
}	
	
function rotateNews() {
	swapImgs();
	if (nrcurrent < nrtotal) {
		nrnext = nrcurrent + 1;
	} else {
		nrnext = 0;
	}
	rotatorpreload.src = newsrotator[nrnext];
	news_timeout = setTimeout("rotateNews()",5000);
}

function stopRotation() {
	clearTimeout(news_timeout);
}

function resumeRotation() {
	news_timeout = setTimeout("rotateNews()",5000);
}

function showNewsItem(newsNumber) {
	if(initialized == 0) {
		return;
	}
	clearTimeout(news_timeout);
	nrnext = newsNumber;
	$("next").src = newsrotator[nrnext];
	var currentli = "nrprev" + nrcurrent;
	var nextli = "nrprev" + nrnext;
	$(currentli).className = "";
	$(nextli).className = "hover";
	$("newstitle").set("html",newstitles[nrnext]);
	$("newsabstract").set("html",newsabstracts[nrnext]);
	$("newslink").href = newslinks[nrnext];
	nrcurrent = nrnext;
}

function changeToPage(path) {
	document.location.href = path;
}

function rating(star) {
	var stars = new Array("one", "two", "three", "four", "five");
	for (  var i = 0; stars[i] != star; i++ ) {
		$(stars[i]).className = "selected";
	}
	$(stars[i]).className = "selected";
}

function unrate() {
	var stars = new Array("one", "two", "three", "four", "five");
	var i = 0;
	while ( star = stars[i] ) {
		$(star).className = "";
		i++;
	}
}

function show(el) {
	$(el).style.display = "";
}

function hide(el) {
	$(el).style.display = "none";
}

function toggle(el) {
	if ($(el).style.display == "") {
		hide(el);
	} else {
		show(el);
	}
}

function openListItem(el) {
	if ( faqcurrent != "" ) {
		hide(faqcurrent);
	}
	if ( faqcurrent == el ) {
		faqcurrent = "";
	} else {
		show(el);
		faqcurrent = el;
	}
}

function slideListItem(el,slider) {
	if ( faqcurrent != "" ) {
		sliderCurrent.slideOut();
	}
	if ( faqcurrent == el ) {
		faqcurrent = "";
	} else {
		slider.slideIn();
		faqcurrent = el;
		sliderCurrent = slider;
	}
}

function highlight(el) {
	$(el).className = $(el).className + " selected";
}

function unlight(el) {
	var myclass = $(el).className;
	$(el).className = myclass.replace(" selected","");
}

function fadein(el,value) {
	var myFx = new Fx.Tween(el, {duration:"short"}).start("opacity",0,value);
}

function fadeout(el,value,removeoverlay) {
  var myFx = new Fx.Tween(el, {duration:"short"});
  if ( removeoverlay != null ) {
    myFx.start("opacity",value,0).chain( function() { removeOverlay() } );
  } else {
    myFx.start("opacity",value,0);
  }
}

function getFullPath(path, filename) {
	return path + filename;
}

function overlay() {
	if ( !($chk($("overlay"))) ) {
    var overlay = new Element("div", {
      id:"overlay"
    });
    overlay.setStyles({
      background:"#000",
      left:0,
      opacity:".5",
      position:"absolute",
      top:0,
      zIndex:2000
    });
    overlay.inject($("wrapper"));
    resizeOverlay("overlay");
    resizeoverlay = function() {
      resizeOverlay("overlay");
    };
    window.addEvent("resize", resizeoverlay);
  }
}

function resizeOverlay(overlay) {
  var wsize = window.getSize();
  var wscroll = window.getScrollSize();
  if ( wsize.y > wscroll.y ) {
    var overlayheight = wsizey;
  } else {
    var overlayheight = wscroll.y;
  }
  var overlaywidth = wsize.x;
  $(overlay).setStyles({
    height:overlayheight + "px",
    width:overlaywidth + "px"
  });
}

function removeOverlay() {
  window.removeEvent("resize", resizeoverlay);
  if ($chk($("overlay"))) {
    var fadeout = new Fx.Tween("overlay", { duration:150 });
    fadeout.start("opacity",.4,0).chain(
      function() {
        var removedoverlay = $("overlay").dispose();
      }
    )
  }
}

function popupImg(path, galleryImgs, galleryTitles, galleryTexts, actual, showbuttons) {
	var filename = galleryImgs[actual];
	showing = actual;
	if ( !($chk($("popup"))) ) {
		overlay();
		var wsize = window.getSize();
		var wscroll = window.getScroll();
		var initX = wsize.x / 2;
		initX = initX.round() - 160;
		var initY = wsize.y / 2;
		initY = initY.round() - 57 + wscroll.y;
		var preload = new Element("img", {src:"/SiteAssets/common/images/preload.gif"});
		var popup = new Element("div", {
			id:"popup"
		});
		popup.setStyles({
			background:"#FFF url(/SiteAssets/common/images/preload.gif) no-repeat center center",
			height:"114px",
			left:initX + "px",
			opacity:0,
			padding:"5px 30px",
			position:"absolute",
			top:initY + "px",
			width:"320px",
			zIndex:"9999"
		});
		popup.inject($("wrapper"));
		var myFx = new Fx.Tween("popup", {duration:"short"});
		myFx.start("opacity",0,1);
		var galleryImg = new Element("img", {
			id:"galleryImg"
		});
		galleryImg.inject($("popup"));
		var fxImgHide = new Fx.Morph("galleryImg").set({"opacity":0});
    if (showbuttons != false) {
      var previousButton = new Element("img", {
        alt:"Previous",
        id:"galleryPrevButton",
        src:"/SiteAssets/portal/images/imgGalleryPrev.png",
        title:"Previous"
      });
      previousButton.setStyles({
        border:"1px solid #FFF",
        cursor:"pointer",
        height:"26px",
        left:"1px",
        opacity:.7,
        position:"absolute",
        top:"50px",
        width:"24px"
      })
      var nextButton = new Element("img", {
        alt:"Next",
        id:"galleryNextButton",
        src:"/SiteAssets/portal/images/imgGalleryNext.png",
        title:"Next"
      });
      nextButton.setStyles({
        border:"1px solid #FFF",
        cursor:"pointer",
        height:"26px",
        opacity:.7,
        position:"absolute",
        right:"2px",
        top:"50px",
        width:"24px"
      })
    }
		var closeButton = new Element("img", {
			alt:"Close",
			id:"galleryCloseButton",
			src:"/SiteAssets/common/images/closePopup.png",
			title:"Close"
		});
		closeButton.setStyles({
			top:"15px",
			cursor:"pointer",
			right:"40px",
			position:"absolute"
		});
    if ( (galleryTitles != null) || (galleryTexts != null) ) {
      var imgData = new Element("div", {
        id:"imgData"
      });
      imgData.setStyles({
        background:"#FFF",
        bottom:"5px",
        color:"#000",
        left:"30px",
        opacity:.7,
        padding:"5px",
        position:"absolute",
        right:"30px"
      });
      var imgDataHide = new Element("a", {
        id:"imgDataHide",
        href:"javascript:void(0)"
      });
      imgDataHide.setStyles({
        color:"#000",
        fontSize:"10px",
        position:"absolute",
        right:"3px",
        top:"1px"
      });
      imgDataHide.set("html","Hide info");
      var imgDataShow = new Element("a", {
        id:"imgDataShow",
        href:"javascript:void(0)"
      });
      imgDataShow.setStyles({
        background:"#FFF",
        color:"#000",
        fontSize:"10px",
        padding:"3px",
        position:"absolute",
        right:"30px",
        bottom:"5px"
      });
      imgDataShow.set("html","Show info");
      imgData.inject($("popup"));
      imgDataHide.inject($("imgData"));
      imgDataShow.inject($("popup"));
      $("imgDataHide").addEvent("click", function() {
        fadeout("imgData",".7");
        showingImgData=false;
        fadein("imgDataShow",".7");
      });
      $("imgDataShow").addEvent("click", function() {
        fadein("imgData",".7");
        showingImgData=true;
        fadeout("imgDataShow",".7");
      });
      if ( galleryTitles !=null) {
        var imgTitle = new Element("div", {
          id:"imgTitle"
        });
        imgTitle.setStyles({
          fontSize:"11px"
        });
        imgTitle.inject($("imgData"));
      }
      if ( galleryTexts != null ) {
        var imgText = new Element("p", {
          id:"imgText"
        });
        imgText.setStyles({
          fontSize:"10px",
          margin:0,
          padding:0
        });
        imgText.inject($("imgData"));
      }
      if (showbuttons != false) {
        previousButton.inject($("popup"));
        nextButton.inject($("popup"));
      }
    }
		closeButton.inject($("popup"));
		$("galleryCloseButton").addEvent("click", function() { closePopupImg(); });
		window.addEvent("resize", function() { changeImg(path,"",galleryTitles,galleryTexts); });
		loadImage(path,filename,galleryTitles,galleryTexts);
	}
}

function loadImage(path,filename,titles,texts) {
	$("popup").setStyles({
		background:"#FFF url(/SiteAssets/common/images/preload.gif) no-repeat center center"
	});
	var imgPath = getFullPath(path,filename);
  if ( titles != null ) {
    var title = titles[showing];
  }
  if ( texts != null ) {
    var text = texts[showing];
  }
	var imgPreloader = new Image();
	imgPreloader.onload = function() {
		setImage(imgPath,(imgPreloader.width), (imgPreloader.height),title,text);
    if ( $("galleryPrevButton") ) {
  		$("galleryPrevButton").addEvent("click", function() { changeImg(path,"prev",galleryTitles,galleryTexts); });
    }
    if ( $("galleryNextButton") ) {
  		$("galleryNextButton").addEvent("click", function() { changeImg(path,"next",galleryTitles,galleryTexts); });
    }
	};
	imgPreloader.src = imgPath;
}

function setImage(imgPath,newWidth, newHeight,title,text) {
	$("popup").setStyles({
		background:"#FFF"
	});
	var myEffect = new Fx.Morph("popup", { duration:"short" });
	var popupcoords = $("popup").getCoordinates();
	var wsize = window.getSize();
	var newX = ((wsize.x - newWidth) / 2).round();
	var wscroll = window.getScroll();
	var newY = (( wsize.y - newHeight) / 2).round() + wscroll.y;
  var newTopPos = (newHeight /2).round() + "px";
  if ( $chk($("galleryPrevButton")) ) {
    var movePrev = new Fx.Tween("galleryPrevButton", { duration:"short" });
    movePrev.start("top",newTopPos);
  }
  if ( $chk($("galleryNextButton")) ) {
    var movePrev = new Fx.Tween("galleryNextButton", { duration:"short" });
    movePrev.start("top",newTopPos);
  }
	myEffect.start({
		height:[popupcoords.height -10, newHeight],
		left:[popupcoords.left, newX],
		top:[popupcoords.top, newY],
		width:[popupcoords.width -60, newWidth]
	}).chain(
		function() {
			$("galleryImg").src = imgPath;
			fadein("galleryImg",1);
      showImgData(title,text);
		}
	);
}

function showImgData(title,text) {
  if ($chk(title)) { $("imgTitle").set("html","<b>" + title + "</b>"); }
  if ($chk(text)) { $("imgText").set("html",text); }
  if ( showingImgData == false ) {
    $("imgData").setStyle("opacity",0);
    $("imgDataShow").setStyle("opacity",.7);
  } else if ($chk(title) || $chk(text)) {
    $("imgData").setStyles({opacity:.7});
    $("imgDataShow").setStyle("opacity",0);
  }
}

function changeImg(path,follow,titles,texts) {
	$("galleryPrevButton").removeEvents();
	$("galleryNextButton").removeEvents();
	if ( follow == "prev" ) {
		var nextImg = getPrevImage(galleryImgs);
	} else if ( follow == "next" ){
		var nextImg = getNextImage(galleryImgs);
	} else {
		nextImg = galleryImgs[showing];
	}
	$("imgData").setStyles({"opacity":0});
	var myFx = new Fx.Tween("galleryImg", {duration:"short"});
	myFx.start("opacity",1,0).chain(
		function() { loadImage(path,nextImg,titles,texts) }
	);
}

function getNextImage(galleryImgs) {
	if ( showing < galleryImgs.length-1 ) {
		showing++;
	} else {
		showing = 0;
	}
	return galleryImgs[showing];
}

function getPrevImage(galleryImgs) {
	if ( showing > 0 ) {
		showing--;
	} else {
		showing = galleryImgs.length-1;
	}
	return galleryImgs[showing];
}

function closePopupImg() {
  $("popup").empty();
	var myFx = new Fx.Morph("popup", {duration:"200"});
	var popupCoord = $("popup").getCoordinates();
	myFx.start({
		"height":[popupCoord.height - 20],
		"left":[popupCoord.left + 10],
		"opacity":0,
		"top":[popupCoord.top + 5],
		"width":[(popupCoord.width - 80)]
	}).chain(
		function() {
      removeOverlay();
			window.removeEvents("resize");
			var removedPopup = $("popup").dispose();
		}
	);
}

function advancedSearch() {
	if ( mySlide.open ) {
		mySlide.slideOut();
	} else {
		mySlide.slideIn();
	}
	try {
	  $("advancedsearch").toggleClass("collapse");
	} catch(e) {
	}
}

function swapcontent(menuitem,elementtoshow) {
  $(current).setStyle("display","none");
  $(currentmenuitem).removeClass("selected");
  $(elementtoshow).setStyle("display","");
  $(menuitem).addClass("selected");
  current = elementtoshow;
  currentmenuitem = menuitem;
}

function scrollTo(to) {
  var children = $("imggallery").getChildren("li");
  if (to == "next") {
    if ( (carrouselshowing+3) <= children.length ) {
      carrouselshowing = carrouselshowing+3;
    }
  } else {
    if ( (carrouselshowing-3) >= 0 ) {
      carrouselshowing = carrouselshowing-3;
    } else {
      carrouselshowing = 0;
    }
  }
  el = children[carrouselshowing];
  myScroll.toElement(el);
}

function goLeft() {
  scrollTo("prev");
}

function goRight() {
  scrollTo("next");
}

function showbrief(container,remote,values) {
  if ( $chk(nowshowingbrief) ) {
    $(nowshowingbrief).empty();
    hide(nowshowingbrief);
  }
  postrequest(container,remote,values);
  nowshowingbrief = container;
}

function getrequest(container,remote,values) {
  var myHTMLRequest = new Request.HTML({url:remote,
		onSuccess: function(html) {
			$(container).adopt(html);
		},
		onFailure: function() {
			$(container).set('text', 'There was an error while trying to retrieve user info.');
		}
	}).get(values);
}

function postrequest(container,remote,values) {
  var myHTMLRequest = new Request.HTML({url:remote,
		onSuccess: function(html) {
			$(container).adopt(html);
		},
		onFailure: function() {
			$(container).set('text', 'There was an error while trying to retrieve user info.');
		}
	}).post(values);
}

/*  Popup overlay  */

/*function openpopup(urltoload) {
    var popup = new Element("div", {
      id:"popupportlet"
    });
    popup.addClass("popupportlet");
    popup.setStyles({
      "opacity":0,
      "display":"",
    });
    popup.inject(document.body);
    var myHTMLRequest = new Request.HTML({url:urltoload,
      onSuccess: function(html) {
        $("popupportlet").empty();
        $("popupportlet").adopt(html);
        overlay();
        showpopup("popupportlet");
      },
      onFailure: function() {
        $("popupportlet").set('html', '<div class="ajaxfailed">There was an error while trying to retrieve user info. <a href="#" onclick="javascript:closepopup(\'popupportlet\')">Close</a></div>');
        overlay();
        showpopup("popupportlet");
      }
    }).get();
  placePop = function() {
    placepopup("popupportlet");
  };
  window.addEvent("resize", placePop);
}

function placepopup(popup) {
  if ($chk(popup)) {
    var myEffect = new Fx.Tween(popup).chain(
      function() { showpopup(popup) }
    );
    myEffect.start("opacity",0);
  }
}

function showpopup(popup) {
  var winSize = window.getSize();
  var winScroll = window.getScroll();
  var popupSize = $(popup).getSize();
  var xpos = (winSize.x - popupSize.x) / 2;
  var ypos = ((winSize.y - popupSize.y) / 2) + winScroll.y;
  $(popup).setStyles({
    left:xpos+"px",
    top:ypos+"px"
  });
  var myEffect = new Fx.Tween(popup);
  myEffect.start("opacity",1);
}

function closepopup() {
  window.removeEvent("resize", placePop);
  var myFx = new Fx.Tween("popupportlet", {duration:"short"});
  myFx.start("opacity",0).chain( function() {
    var removedPopup = $("popupportlet").dispose();
    removeOverlay();
  });
}

function closeerrormsg(container) {
  if ( $chk($(container)) ) {
    $(container).set("text","");
  }
}*/

/* END Popup pverlay  */

/*  Iframe Overlay  */

function openiframe(pagetoopen) {
  overlay();
  var iframecontainer = new Element("div", {
    id:"createprofilecontainer",
    styles: { opacity:0 }
  });
  var miframe = new IFrame({
    events: {
      load: function() {
        placeIf = function() {
          placeiframe("floatingiframe");
        };
        window.addEvent("resize", placeIf);
        showiframe("floatingiframe");
      }
    },
    id:"floatingiframe",
    name:"floatingiframe",
    scrolling:"no",
    src:pagetoopen
  });
  iframecontainer.addClass("iframecontainer");
  miframe.addClass("iframe");
  iframecontainer.inject("wrapper");
  miframe.inject("createprofilecontainer");
}

function iframecontentsize(el) {
  parent.iframeContentSize = $(el).getScrollSize();
}

function placeiframe(iframe) {
  if ($chk(iframe)) {
    var iframecontainer = $(iframe).getParent();
    var myEffect = new Fx.Tween(iframecontainer).chain(
      function() { showiframe(iframe, iframeContentSize) }
    );
    myEffect.start("opacity",0);
  }
}

function showiframe(iframe) {
  var iframecontainer = $(iframe).getParent();
  var winSize = window.getSize();
  var xpos = (winSize.x - iframeContentSize.x) / 2;
  var ypos = (winSize.y - iframeContentSize.y) / 2;
  var height = 35 + iframeContentSize.y;
  $(iframecontainer).setStyles({
    left:xpos+"px",
    top:ypos+"px"
  });
  $(iframe).setStyle("height",height);
  var myEffect = new Fx.Tween(iframecontainer);
  myEffect.start("opacity",1);
}

function closeiframe(iframe, reload) {
  window.removeEvent("resize", placeIf);
  var iframecontainer = $(iframe).getParent();
  var myEffect = new Fx.Tween(iframecontainer).chain(
    function() {
      $(iframecontainer).destroy();
      removeOverlay();
    });
  myEffect.start("opacity",0);
  window.location.reload();
}

/* END iframe overlay  */


/* Avatar Selector */

function deselectall(ul,hiddenformfield) {
  $(hiddenformfield).value = "";
  var els = $(ul).getChildren("li");
  var i = 0;
  while ( el = els[i] ) {
    el.removeClass("selected");
    i++;
  }
}

function changeSelectedAvatar(ul,selectedavatar,browsefield,hiddenformfield,valuetosave) {
  deselectall(ul,hiddenformfield);
  $(browsefield).setProperty("value","");
  $(selectedavatar).addClass("selected");
  $(hiddenformfield).value = valuetosave;
}

/* END Avatar Selector */

function textLimit(field, maxlen) {
  if (field.value.length > maxlen + 1) {
     if (field.value.length > maxlen) {
        field.value = field.value.substring(0, maxlen);
     }
  }
}

/* Mockup purposes only */


function showlinkaccount() {
  $("createprofile").fade("out");
  showpopup("linkaccount");
}

function linkaccount() {
  if ( $("linkaccounterrormsg").get("text") == "" ) {
    showerrormsg('linkaccounterrormsg','Username and password do not match.');
  } else {
    $("linkaccount").fade("out");
    showpopup("linkingok");
  }
}

/* ALERTS */

function confirmmessage(msg,dest) {
	var r=confirm(msg);
	if (r==true) {
		window.location.href = dest;
	}
}

/* INVITE TO MY CLAN LIST */
function invitetomyclanlist() {
	if ( mySlide.open ) {
		mySlide.slideOut();
	} else {
		mySlide.slideIn();
	}
	$("invitetomyclanlist").toggleClass("collapse");
}
/*Function to handle the error image when cames from uknoow sources.*/
function handleErrorImage(objImg) {
  objImg.src = '/SiteAssets/common/images/pix.png';
	objImg.onerror = null;
}
