/*********************************************************
*	toggleObject
*	toggle object from block to none and vice versa
*
**********************************************************/
arrowToggle=new Image();  arrowToggle.src="shared/gfx/archiveArrow.gif"; 
arrow = new Image(); arrow.src="shared/gfx/archiveArrowCol.gif";

function toggleObject(obj){

    if(document.getElementById(obj).style.display == 'block'){
      	document.getElementById(obj).style.display = 'none';
		if (document.images) eval('document.img_' + obj + '.src=arrow.src'); //document.title="close";
   	}else{
      		document.getElementById(obj).style.display = 'block';
			if (document.images) eval('document.img_' + obj + '.src=arrowToggle.src'); //document.title="open";
   	}

}

/*********************************************************
*	login.js
*	common javascript functions used to login/out users
*
**********************************************************/



/*********************************************************
*	showLogin
*	
**********************************************************/
function showLogin() {
	document.getElementById("searchlogin").style.visibility = "hidden"; 
	document.getElementById("liveSearch").style.visibility = "hidden";
	resize('wrap-searchlogin',100,200,200);
	document.getElementById("login").style.visibility = "visible"; 
}


/*********************************************************
*	hideLogin
*	
**********************************************************/
function hideLogin() {
document.getElementById("login").style.visibility = "hidden";
resize('wrap-searchlogin',22,200,200);
document.getElementById("searchlogin").style.visibility = "visible"; 
}

/*********************************************************
*	usrLogin
*	Check user cred against dbinfo -using AJAX
**********************************************************/
function usrLogin(callback){

hideLogin();
document.getElementById("loginstate").innerHTML=callback;
LoadPage('shared/assets/loadBlog.php','content');
document.getElementById("bruker").value="brukarnavn";
document.getElementById("passord").value="passord";
}

function usrLoginKeyEvent(){
	postDataReturnText('shared/assets/usrLogin.php', 'u=' + document.login.bruker.value + '&p=' + document.login.passord.value + '&a=login', usrLogin);
}


/*********************************************************
*	usrLogout
*	Logging out user -using AJAX
**********************************************************/
function usrLogout(){
document.getElementById("loginstate").innerHTML=xmlHttp.responseText;
LoadPage('shared/assets/loadBlog.php','content');
}

/*********************************************************
*	resize
*	resizes an object given by id to new height(hNEW) 
*	and new width(wNEW) during time(millisec)
*	require getHYP();, doResize();
**********************************************************/

function resize(id, hNEW, wNEW, millisec){

	var speed = Math.round(millisec / 100); 
    var timer = 0;
	var yFAC=0;
	var xFAC=0;
	var hFAC=0;
	var dFAC=0;
	var xNEW=0;
	var yNEW=0;
	var newWidth=0;
	var newHeight=0;

    var obj = document.getElementById(id);
	var wOLD = parseInt(getStyle(obj, "width"));
	var hOLD = parseInt(getStyle(obj, "height"));
	
	yFAC = hNEW - hOLD;
	xFAC = wNEW - wOLD;
	
	hFAC = getHYP(xFAC,yFAC);
	
	dFAC = Math.atan(xFAC / yFAC);

	for(i = 1; i <= hFAC; i++ ){ 

		if(hNEW<hOLD)
			newHeight = hOLD - Math.ceil(( i * Math.cos( dFAC )));
		if(hNEW>=hOLD)
			newHeight = hOLD + Math.ceil(( i * Math.cos( dFAC )));
		if(wNEW<wOLD)
			newWidth = wOLD - Math.ceil(( i * Math.sin( dFAC )));	
		if(wNEW>=wOLD)
			newWidth = wOLD + Math.ceil(( i * Math.sin( dFAC )));	
			
		setTimeout("doResize(" + newHeight + "," + newWidth + ",'" + id + "')",(timer * speed)); 
        timer++;
		}
}

/*********************************************************
*	getHYP
*	Finds Hypotinus of a rectangle given side x and y
*	used by resize();
**********************************************************/

function getHYP(x,y){
	return Math.ceil(Math.sqrt(x*x+y*y));
}

/*********************************************************
*	doResize
*	Sets HÈIGHT and WIDHT to an object(id) given by 
*	newHeight and newWidth. .
**********************************************************/

function doResize(newHeight, newWidth, id) { 
	
    var object = document.getElementById(id).style; 
    object.height = newHeight + "px"; 
    object.width = newWidth + "px"; 
}

/*********************************************************
*	getStyle
*	Gets style(Style) from an object(el) 
*	required toCamelCase
**********************************************************/

function getStyle(el, style) {
   if(!document.getElementById) return;

     var value = el.style[toCamelCase(style)];

    if(!value)
        if(document.defaultView)
            value = document.defaultView.
                 getComputedStyle(el, "").getPropertyValue(style);

        else if(el.currentStyle)
            value = el.currentStyle[toCamelCase(style)];

     return value;
}

/*********************************************************
*	setStyle
*	Sewts an object's(objId) style(style) to value(value)
**********************************************************/


function setStyle(objId, style, value) {
    document.getElementById(objId).style[style] = value;

}

/*********************************************************
*	toCamelCase
*	???
**********************************************************/

function toCamelCase( sInput ) {
    var oStringList = sInput.split('-');
    if(oStringList.length == 1)    
        return oStringList[0];
    var ret = sInput.indexOf("-") == 0 ? 
       oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1) : oStringList[0];
    for(var i = 1, len = oStringList.length; i < len; i++){
        var s = oStringList[i];
        ret += s.charAt(0).toUpperCase() + s.substring(1)
    }
    return ret;
}




/*********************************************************
*	checkKey
*	check if keyevent is key
*********************************************************/
function checkEnter(e, key, callback,data){ //e is event object passed from function invocation
var characterCode //literal character code will be stored in this variable

if(e && e.which){ //if which property of event object is supported (NN4)
e = e
characterCode = e.which //character code is contained in NN4's which property
}
else{
e = event
characterCode = e.keyCode //character code is contained in IE's keyCode property
}

if(characterCode == key){ //if generated character code is equal to ascii code in key
callback(data);
return false 
}
else{
return true 
}

}


/*********************************************************
*	togglePrivate
*	Sets post private og public
*********************************************************/
function togglePrivate(callback){
	
	
	var ids=callback.split(":");
	//alert(ids);
	
	// PRELOADING IMAGES
	 img_open =new Image();  img_open.src ="shared/gfx/private_open.gif"; 
	 img_closed=new Image();  img_closed.src="shared/gfx/private_closed.gif"; 

	var toggleImg = document.getElementById('img' + ids[0]);

//brukar tilbakemelding fra php
if(ids[1]==0)
	toggleImg.setAttribute('src', img_closed.src);
else
	toggleImg.setAttribute('src', img_open.src);

}


/*****add post ***/ 
function createQuestion(){
	nr=0;
       var qTEXT = newElement("input",{type:"text",name:"qTEXT",value:"spørsmål",id:"txt_qTEXT",onclick:"if(this.value=='spørsmål') this.value=''",onblur:"if(this.value=='') this.value='spørsmål'",onfocus:"if(this.value=='spørsmål') this.value=''"});
	   var qSUB1 = newElement("input",{type:"text",name:"qSUB",value:"alternativ #1",id:"txt_qSUB",onclick:"if(this.value=='alternativ #1') this.value=''",onblur:"if(this.value=='') this.value='alternativ #1'",onfocus:"if(this.value=='alternativ #1') this.value=''"});
	   var imgADD = newElement("image",{src:"shared/gfx/add_Q_alt.gif",alt:"Legg til Alternativ",id:"addIMG",onclick:"add_qSUB()"});

		resize('overlayBox',535,400,100);
		setStyle('btn_addQ','display','none');

       	document.getElementById("Q").appendChild(qTEXT);
	   	document.getElementById("Q").appendChild(qSUB1);
		document.getElementById("Q").appendChild(imgADD);

}

function isNameQuirk(){
  var elem1 = document.createElement("div");
  var elem2 = document.createElement("input");
  elem2.type = "hidden";
  elem2.name = "testName";
  elem1.appendChild(elem2);
  var isQuirk = (elem1.innerHTML.indexOf("test") == -1);
  isNameQuirk = function() {return isQuirk;}
  return isNameQuirk();
}

function newElement(type,att,evts,appendToObj){

        var elem;
        if(isNameQuirk() && att.name != null){
          elem = document.createElement('<' + type + ' name="' + att.name + '">');
        }
        else{
          elem = document.createElement(type);
        }
       
        for(var prop in att){
          elem.setAttribute(prop,att[prop]);
        }

        if(evts){
          for(var evt in evts){
            elem[evt] = evts[evt];
          }
        }

        if(appendToObj){
          appendToObj.appendChild(elem);
        }

        return elem;

}

var nr=0; //BRUKT I sub_addQ

function add_qSUB(){
	
	

	
nr=nr+1;
snr=nr+1;
if(nr>='5'){

}else{
	
	var obj = document.getElementById('overlayBox');
	var wHeight = parseInt(getStyle(obj, "height"));
	var wWidth = parseInt(getStyle(obj, "width"));
		
	//var wHeight=540;//parseInt(getStyle("overlayBox", "height"));

	resize('overlayBox', wHeight + 20,wWidth,100);
	
   var qSUB = newElement("input",{type:"text",name:"qSUB",value:"alternativ #" + snr,id:"txt_qSUB",onclick:"if(this.value=='alternativ #" + snr + "') this.value=''",onblur:"if(this.value=='') this.value='alternativ #" + snr + "'",onfocus:"if(this.value=='alternativ #" + snr + "') this.value=''"});

 	document.getElementById("Q").appendChild(qSUB);
//	document.getElementById("Q").appendChild(imgADD);
}

}

/*********************************************************
*	insertatCursor
*	sett text inn i ein textbox el. der cursoren er
**********************************************************/
function insertAtCursor(myField, myValue) {
 //erher må vi utvide til å markere text og innkapsle den i ein tag.
//IE support 

obj = document.getElementById(myField);

switch (myValue){
		
	case "ImgTag":
	myValue="<img src=\"link_til_bilde\" alt=\"\">";
	break;

	case "ImgTagZoom":
	myValue="<a href=\"link_til_thumbbilde\"><img src=\"link_til_bilde\"></a>";
	break;
	
	case "LinkTag":
	myValue="<a href=\"http://din.link\" target=\"_blank\">din_tekst</a>";
	break;

	case "TooltipTag":
	myValue="ikkje tilgjengleg enda";
	break;
	
	case "iTag":
	myValue="<i></i>";
	break;

	case "bTag":
	myValue="<b></b>";
	break;

	case "uTag":
	myValue="<u></u>";
	break;
	
	
	

}

//IE support
	if (document.selection) { 
			obj.focus();
			//in effect we are creating a text range with zero 
			//length at the cursor location and replacing it 
			//with myValue 
			sel = document.selection.createRange(); 
			sel.text = myValue; 
	}
	else if (obj.selectionStart || obj.selectionStart == '0') { 	
		//Mozilla/Firefox/Netscape 7+ support 
		//Here we get the start and end points of the 
		//selection. Then we create substrings up to the 
		//start of the selection and from the end point 
		//of the selection to the end of the field value. 
		//Then we concatenate the first substring, myValue, 
		//and the second substring to get the new value. 

		var startPos = obj.selectionStart; 
		var endPos = obj.selectionEnd; 
		obj.value = obj.value.substring(0, startPos)+ myValue+ obj.value.substring(endPos, obj.value.length); 
	} else { 
		obj.value += myValue; 
	}

	

}	

function deletePost(callback){
	LoadPage('shared/scripts/php/loadBlog.php','contentBlog');
	//updateBlogArchive();
	
}

function NewPostCreate(sid) {

xmlHttp=GetXmlHttpObject();
if (xmlHttp==null){
	 alert ("Browser does not support HTTP Request")
	 return
}

var content= urlencode(document.getElementById('blogContent').value);

var poststr = "Title=" + document.getElementById('blogTitle').value + "&Content=" +  content;

if(document.getElementById('txt_qTEXT')) poststr=poststr+ "&qTEXT="+document.getElementById('txt_qTEXT').value;

var alternatives=document.getElementsByName("qSUB");
var strippedAlt = new Array();

for (var j=0; j < alternatives.length; j++) {
	if(alternatives[j].value!='alternativ #1' && alternatives[j].value!='alternativ #2' && alternatives[j].value!='alternativ #3' && alternatives[j].value!='alternativ #4' && alternatives[j].value!='alternativ #5')
	var dummy = strippedAlt.push(alternatives[j].value); 
};

for (var i=0; i < strippedAlt.length; i++) {
	 poststr=poststr + "&qSUB"+i+"="+escape(strippedAlt[i]);
};
var url="shared/scripts/php/newPost.php"
url=url+"?" + poststr;
url=url+"&sid="+sid;

//document.getElementById('debug').innerHTML = url;

xmlHttp.onreadystatechange=function(){
//Check page is completed and there were no problems.
if ((xmlHttp.readyState == 4) && (xmlHttp.status == 200)) {
	if(xmlHttp.responseText=='OK'){
		//updateBlogArchive();
		closeoverlayBox(); 
		LoadPage('shared/scripts/php/loadBlog.php','contentBlog');
	}
	document.getElementById('overlayBox').innerHTML = xmlHttp.responseText + ' <a href="javascript:closeoverlayBox()">lukk</a>';
    }

}


xmlHttp.open("GET",url,true)
xmlHttp.send(null)


}

/*********************************************************
*	urlencode
*	encpdes url for use inn addr-
*
**********************************************************/

function urlencode( str ) {
                           
    var histogram = {}, histogram_r = {}, code = 0, tmp_arr = [];
    var ret = str.toString();
    
    var replacer = function(search, replace, str) {
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
    };
    
    // The histogram is identical to the one in urldecode.
    histogram['!']   = '%21';
    histogram['%20'] = '+';
    
    // Begin with encodeURIComponent, which most resembles PHP's encoding functions
    ret = encodeURIComponent(ret);
    
    for (search in histogram) {
        replace = histogram[search];
        ret = replacer(search, replace, ret) // Custom replace. No regexing
    }
    
    // Uppercase for full PHP compatibility
    return ret.replace(/(\%([a-z0-9]{2}))/g, function(full, m1, m2) {
        return "%"+m2.toUpperCase();
    });
    
    return ret;
}

function reloadPost(pid){
document.title=pid;
}




function previewPost(id){

    var object = document.getElementById("postPreview").style; 
    object.display = "block";

	loadPost(id,'postPreview');
}

function hidepreviewPost(){
    var object = document.getElementById("postPreview").style; 
    object.display = "none";

}

function loadPost(id, target){

	//show loading in spesific post
	xmlHttp=GetXmlHttpObject();
		var url="shared/assets/loadPost.php";
		url=url+"?id=" + id;
		
		document.getElementById(target).innerHTML = '<center><br><br><br><img src="graphics/ajax-load.gif"><br><br><br></center>'; 
		xmlHttp.onreadystatechange=function(){
			//Check page is completed and there were no problems.
			if ((xmlHttp.readyState == 4) && (xmlHttp.status == 200)) document.getElementById(target).innerHTML = xmlHttp.responseText;
		}
		xmlHttp.open("GET",url,true);
		xmlHttp.send(null);

}

function openMenu(){
resize('userMenu',250,800,200);
LoadPage('shared/assets/userMenu.php','userMenu')
}

function closeMenu(){
resize('userMenu',20,800,200);
document.getElementById(target).innerHTML
}
