﻿var mousepos = null;
var windowsize = null;
var isIE = (navigator.userAgent.indexOf("MSIE") >= 0);

if (document.layers) {
    document.captureEvents(Event.MOUSEMOVE);
    document.onmousemove = captureMousePosition;
} else if (document.all) {
    document.onmousemove = captureMousePosition;
} else if (document.getElementById) {
    document.onmousemove = captureMousePosition;
}

window.scrollTo = function() { }

function captureMousePosition(e) {
    if(!e) 
    {
        e = window.event; 
    } 
    if(!e||(typeof(e.pageX)!='number'&&typeof(e.clientX)!='number')) 
    { 
        mousepos = {x:0,y:0};
    }
    
    if (document.layers) {
        if(e)
        {
            mousepos = {x:e.pageX,y:e.pageY};
        }
    } 
    else if (document.all && document.body) 
    {
        mousepos = {x:e.clientX+document.documentElement.scrollLeft,y:e.clientY+document.documentElement.scrollTop};
    } 
    else if (document.getElementById) 
    {
        if(e)
        {
            mousepos = {x:e.pageX+window.pageXOffset,y:e.pageY+window.pageYOffset};
        }
    }
    capturePageDimensions();
}

function capturePageDimensions(){
	if(document.body){
	    // code based on lightbox.js
	    var xScroll, yScroll;
    	
	    if (window.innerHeight && window.scrollMaxY) {	
		    xScroll = document.body.scrollWidth;
		    yScroll = window.innerHeight + window.scrollMaxY;
	    } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		    xScroll = document.body.scrollWidth;
		    yScroll = document.body.scrollHeight;
	    } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		    xScroll = document.body.offsetWidth;
		    yScroll = document.body.offsetHeight;
	    }
    	
	    var windowWidth, windowHeight;
	    if (self.innerHeight) {	// all except Explorer
		    windowWidth = self.innerWidth;
		    windowHeight = self.innerHeight;
	    } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		    windowWidth = document.documentElement.clientWidth;
		    windowHeight = document.documentElement.clientHeight;
	    } else if (document.body) { // other Explorers
		    windowWidth = document.body.clientWidth;
		    windowHeight = document.body.clientHeight;
	    }	
    	
	    // for small pages with total height less then height of the viewport
	    if(yScroll < windowHeight){
		    pageHeight = windowHeight;
	    } else { 
		    pageHeight = yScroll + 50;
	    }

	    // for small pages with total width less then width of the viewport
	    if(xScroll < windowWidth){	
		    pageWidth = windowWidth;
	    } else {
		    pageWidth = xScroll;
	    }

        var scrollLeft, scrollTop;
		if(window.pageXOffset) {
		    scrollLeft = window.pageXOffset;
		    scrollTop = window.pageYOffset;
		}
		else if(document.documentElement) {
		    scrollLeft = document.documentElement.scrollLeft;
		    scrollTop = document.documentElement.scrollTop;
		}
		else if(document.body) {
		    scrollLeft = document.body.scrollLeft;
		    scrollTop = document.body.scrollTop;
		}
		
        windowsize = {
            width:pageWidth,
            height:pageHeight,
            windowWidth:windowWidth,
            windowHeight:windowHeight,
            scrollTop:scrollTop,
            scrollLeft:scrollLeft
        }
    }
}


var _alert = window.alert;

window.alert = function(message,title) 
{
    var alertdiv = ($get("alertdiv")?$get("alertdiv"):document.createElement('div'));
    alertdiv.id = "alertdiv";
    alertdiv.style.display = "none";
    alertdiv.className = "maindialogerror";
    alertdiv.innerHTML = '<table class="alertdialogtable"><tr><td class="alertdialogtd">' + message + '</td></tr><tr><td><input type="button" onclick="CloseDialog()" value="Ok" /></td></tr><table>';
    document.body.appendChild(alertdiv);
    OpenDialog('alertdiv',400,150,title,CloseDialog,null)
}

function getStyle( element, style ) 
{ 
	var value = element.style[style]; 
    if (!value) { 
      if (document.defaultView && document.defaultView.getComputedStyle) { 
		var css = document.defaultView.getComputedStyle(element, null); 
        value = css ? css.getPropertyValue(style) : null; 
      } else if (element.currentStyle) { 
		value = element.currentStyle[style]; 
      } 
     }
     return  value; 
}

function ChangeHover(ctrl,cssclass,hover)
{
    if(hover) {
        if(!Sys.UI.DomElement.containsCssClass(ctrl, cssclass)){
            Sys.UI.DomElement.addCssClass(ctrl,cssclass);
        }
    }
    else {
        if(Sys.UI.DomElement.containsCssClass(ctrl,cssclass)){
            Sys.UI.DomElement.removeCssClass(ctrl,cssclass);
        }
    }
}

function GetElementsByClassName(tagname,classname)
{
    if (!document.getElementsByTagName) return;
    var obj= document.getElementsByTagName(tagname);
    for (var i=0; i < obj.length; i++){
        if (obj[i].className == classname){
          return obj[i];
        }
    }  
}

//Dialog functions
var dialogtargetid = null;

function OpenDialog(id,width,height,title,closeaction,infoaction)
{
    dialogtargetid = id;
    
    var dialog = $get("maindialog");
    var inner = $get("maindialoginner");
    var contentholder = $get("maindialogcontent");
    var dialogtitle = $get("maindialogtitle");
    var closebutton = $get("maindialogclosebutton");
    var infobutton = $get("maindialoginfobutton");
    
    var target = $get(dialogtargetid);
    
    // set height and width of the dialog
    inner.style.width = width + "px";
    inner.style.height = height + "px";
    
    //append inner content for dialog
    if(target)
    {
        for(var i=target.childNodes.length;i>0;i--)
        {
            contentholder.appendChild(target.childNodes[i-1]);
        }
    }
    else
    {
        var errordiv = ($get("errordiv")?$get("errordiv"):document.createElement('div'));
        errordiv.id = "errordiv";
        errordiv.className = "maindialogerror";
        errordiv.innerHTML = "target element not found";
        contentholder.appendChild(errordiv);
    }
    
    //set title
    if(title)
    {
        dialogtitle.innerHTML = title;
    }
    else
    {
        dialogtitle.innerHTML = "Softportal";
    }
    
    // set closeaction
    if(closeaction)
    {
        closebutton.onclick = closeaction;
    }
    else
    {
        closebutton.onclick = CloseDialog;
    }
    
    // set infoaction
    if(infoaction)
    {
        infobutton.onclick = infoaction;
        infobutton.style.display = "block";
    }
    else
    {
        infobutton.style.display = "none";
    }
    
    // set dialog visible
    dialog.style.display = "block";
    inner.style.display = "block";
    
    //add floating behavior
    var floatingBehavior = null;

    var draggable = $get('maindialogdraggable');
    if(draggable){
        if(inner._behaviors != null) {
            floatingBehavior = inner._behaviors[0];
            floatingBehavior.set_handle(draggable);
        }
        else
        {
            floatingBehavior = new Sys.Preview.UI.FloatingBehavior(inner);
            floatingBehavior.set_handle(draggable);
            floatingBehavior.initialize();
            floatingBehavior.drop = CheckFloatingPosition;
        }
    }
    
    Resize();
}

function CheckFloatingPosition()
{
    var dialog = $get('maindialoginner');
    if(dialog)
    {
        var dt = getStyle(dialog,'top');
        var dl = getStyle(dialog,'left');
        
        var resize = false;
        
        if(dt.length>0) {
            var t = parseInt(dt.substring(0,dt.length-2));
            if(t + 150 > windowsize.height)
            {
                dialog.style.top = windowsize.height - 150 + 'px';
                resize = true;
            }
            else
            {
                if(t < 0)
                {
                    dialog.style.top = 0 + 'px';
                }
            }
        }
        if(dl.length>0 && resize == false) {
            var l = parseInt(dl.substring(0,dl.length-2));
            if(l < 0)
            {
                dialog.style.left= 0 + 'px';
            }
            else
            {
                if(l+150 > windowsize.width)
                    dialog.style.left = windowsize.width - 150 + 'px';
            }
        }
    }
}

function CloseDialog()
{
    var dialog = $get("maindialog");
    var inner = $get("maindialoginner");
    var contentholder = $get("maindialogcontent");
    var closebutton = $get("maindialogclosebutton");
    var infobutton = $get("maindialoginfobutton");
    
    var target = $get(dialogtargetid);
    
    //hide dialog
    dialog.style.display = "none";
    inner.style.display = "none";
    
    // move innercontent back to its holder
    if(target)
    {
        for(var i=contentholder.childNodes.length;i>0;i--)
        {
            target.appendChild(contentholder.childNodes[i-1]);
        }
    }
    else
    {
        contentholder.removeChild($get("errordiv"));
    }
    
    //reset actions
    closebutton.onclick = null; 
    infobutton.onclick = null;
}

function Resize()
{
    if($get('maindialog') && getStyle($get('maindialog'),"display")!="none") {
        capturePageDimensions();
        
        var dialog = $get("maindialog");
        var inner = $get("maindialoginner");
        var contentholder = $get("maindialogcontent");
    
        //set height and width of the dialog cover
        dialog.style.width = windowsize.width + "px";
        dialog.style.height = windowsize.height + "px";
        
        var dialogwidth = parseInt(inner.style.width.replace('px',''));
        var dialogheight = parseInt(inner.style.height.replace('px',''));
        
        // set position of the dialog centered
        inner.style.left = Math.floor(windowsize.windowWidth / 2 - (dialogwidth/2)) + "px";
        inner.style.top = Math.floor(windowsize.scrollTop + (windowsize.windowHeight / 2) - (dialogheight/2)) + "px";
        
        //set height of content holder
        contentholder.style.height = (dialogheight-30) + "px";
    }
}

// validation
function OpenCommentForm(controlid)
{
    for(var i=commentformids.length-1;i>=0;i--)
    {
        if(commentformids[i]!=controlid)
        {
            $get(commentformids[i]).style.display="none";
        }
    }
    
    if($get(controlid).style.display=="none")
    {
        $get(controlid).style.display="block";
        $get(controlid.replace("commentform","TextBoxComment")).focus();
    }
    else
    {
        $get(controlid).style.display="none";
    }
}

function CheckField(textbox){

  var result = true;
  
  if(textbox.value.length <= 0){
      result = false;
  }
  
  return result;
}

function CheckEmail(field) {
  var str = field.value; // email string
  var reg2 = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?)$/; // valid
  if (reg2.test(str)) { // if syntax is valid
    return true;
  }
  field.focus();
  field.select();
  return false;
}


// comment form

function AddComment(id,type)
{
    var comment = $get("valcomment");
    var username = $get("valusername");
    var email = $get("valemail");
    var website = $get("valwebsite");
    
    var check = true;
    
    if(CheckField(comment)==false){check = false;}
    if(CheckField(username)==false){check = false;}
    if(CheckField(email)==false){check = false;}
    
    if(check)    
    {
        if(CheckEmail(email)==false)
        {
            alert(email.value + " is an invalid email address.");
        }
        else
        {   
            if(type=="photo")
            {
                SoftPortal.Web.UiService.AddComment(id, type, comment.value, username.value, email.value, website.value, AddCommentComplete);
            }
        }
    }
    else
    {
        alert("Please fill in a comment, your name and your (valid) email address.");
    }
}

function AddCommentComplete(res)
{
    $get("previouscomments").innerHTML = res;
    $get("valcomment").value = "";
}

function SetUiLanguage(lang)
{
    SoftPortal.Web.UiService.SetUiLanguage(lang, SetUiLanguageComplete);
}

function SetUiLanguageComplete(res)
{
    window.location = window.location;
}

//Image rotator functions
var rotateimages = null;
var rotateimageindex = null;
var rotatetimer = null;
function InitImageRotator(albumid, position)
{
    switch(position)
    {
        case 1: 
            $get("imagerotator").style.cssFloat = "left";
            $get("imagerotator").style.styleFloat = "left";
            break;
        case 2:
            $get("imagerotator").style.cssFloat = "right";
            $get("imagerotator").style.styleFloat = "right";
            break;
    }

    SoftPortal.Web.UiService.GetAlbum(albumid, 2, GetAlbumComplete);
}

function GetAlbumComplete(album)
{
    rotateimages = new Array();
    rotateimageindex = 0;
    
    //the image object
	this.clsImg = function(id, url, isportrait)
	{
	    this.id = id;
	    this.url = url;
	    this.isportrait = isportrait;
	}
	
	//alert(album.thumbnails.length);
    if(album.thumbnails.length>0)
    {
        for ( var i=0; i<album.thumbnails.length; i++ )
	    {
	        var thumb = album.thumbnails[i];
	        //rotateimages[rotateimages.length] = new this.clsImg(thumb.id,thumb.url,thumb.portrait);
	        rotateimages.push(new this.clsImg(thumb.id,thumb.url,thumb.portrait));
	    }
    }
    
    rotatetimer = setTimeout("RotateImage()",0);
}

function RotateImage() {
    clearTimeout(rotatetimer);
    
    if(rotateimages) {
        
        if(rotateimageindex == rotateimages.length) {
            rotateimageindex = 0;
        }
        
        $get("rotateimage").src = rotateimages[rotateimageindex].url;

        rotateimageindex +=1;
    }
    rotatetimer = setTimeout("RotateImage()",5000);
}
