sortableReordered = false;
isDragging = false;
mpHideT = 0;
firstLoad = true;
currPage = 0;

function objShow(obj) {
var temp = "";
for (x in obj)
        temp += x + ": " + obj[x] + "\n";
alert (temp);
}

function doChallengeResponse() {
	str = $('login').username.value + ":" +
	MD5($('login').password.value) + ":" +
	$('login').challenge.value;
	$('login').response.value = MD5(str);
	$('login').password.value = "";

  	  var selectedImgs = $('images-container').getElementsByClassName('images');
      var unselectedImgs = $('images-container').getElementsByClassName('images_selected');
	  allImgs = selectedImgs.concat(unselectedImgs);

      var allPages = $('list').getElementsByClassName('pp_p');
	
	if (allImgs.length > 0 || allPages.length > 0) {
        var prompt;
		prompt = 'Kot neprijavljen uporabnik ste že začeli ustvarjati novo knjigo\n\n';
		prompt += 'Če želite nadaljevati s trenutnim delom, potem kliknite V redu (OK).\n';
		prompt += 'Če želite naložiti prejšnjo knjigo, potem kliknite Prekliči (Cancel).';
		if (confirm(prompt)) {
			$('login').restore_session.value = 0;
		} else {
			$('login').restore_session.value = 1;
		}
	}
	return true;
}

function ajaxDebug() {
/*  new Ajax.Request("test.php", {
  	method: 'get',
	onSuccess: function(t) {
  	alert(t.responseText);
	}
  });
*/
}

function sortableGotoURL(url) {
	if (sortableReordered) {       
		sortableReordered = false;
	} else {
		document.location.href=url;
	}
}

function sortableSwitchPage(page_num) {
	if (sortableReordered) {       
		sortableReordered = false;
	} else {
		var url = switch_page_ajax_update_script + "&page_num="+page_num;
		$('indicator').show();
		new Ajax.Updater('div_workimage', url, {onComplete:function(request){new Effect.Highlight('pp_'+page_num,{});}, evalScripts:true, asynchronous:true});
		prev = $('pp_'+var_page_num);
		curr = $('pp_'+page_num);
		if (prev) prev.removeClassName("pp_active");
		if (curr) curr.addClassName("pp_active");
	}
}

function addPage(page_type) {
	var url = add_page_ajax_update_script + "&page_type="+page_type;
	new Ajax.Updater('list-container', url, {onComplete:function(request){sortableSwitchPage(1000);}, evalScripts:true, asynchronous:true});
	toggleMenu('add_page_menu');
}

function deletePage(page_num) {
	if (confirm("Ali res želite izbrisati trenutno stran?")) {
		var url = del_page_ajax_update_script + "&page_num="+page_num;
		new Ajax.Updater('list-container', url, {onComplete:function(request){sortableSwitchPage(-1);}, evalScripts:true, asynchronous:true});
		hiliteUsedImages();
	}
}

function switchTemplate(template) {
	if (confirm("Z menjavo predloge boste izbrisali trenutno dodane strani in prekinili aktivne prenose slik. Že prenesene slike bodo ostale nedotaknjene.\nAli želite menjati predlogo sedaj?")) {
		window.location.href = "index.php?action=switch_template_fajax&new_template="+template;
	}
}

function toggleMenu(obj) {
obj = $(obj);
  if (obj.visible()) {
  	new Effect.BlindUp(obj, {duration:.5, fps:20 })
   } else {
  	new Effect.BlindDown(obj, {duration:.5, fps:20 })  
  };
}

function refreshBgList() {
	var url = bg_list_update_script;
	new Ajax.Updater($('tabContent0'), url, {onComplete:function(request){ }, evalScripts:false, asynchronous:true});

}

function hideMenu(obj) {
  obj = $(obj);
  if (!obj) return false;
    if (obj.visible()) {
        new Effect.BlindUp(obj, {duration:.5, fps:20 });
    }
}

function reloadImage(params) {
    var now = new Date();
    if (document.images) {
		Element.show('indicator');
        $('work_image').src = 'show_workimage.php?' + params + '&t=' + now.getTime();
    }
}

function hiliteUsedImages() { // iz serverja potegne spisek vseh uploadanih fotk na vseh straneh in ze uporabljene postriha zeleno
  var url = used_images_ajax_update_script;
  new Ajax.Request(url, {
  	method: 'get',
	onSuccess: function(t) {
  	  var usedImgs = $w(t.responseText); 
  	  var selectedImgs = $('images-container').getElementsByClassName('images');
      var unselectedImgs = $('images-container').getElementsByClassName('images_selected');
	  
	  allImgs = $A(selectedImgs).concat($A(unselectedImgs));
		
	  if (allImgs.length == 0) { toggleInfoBubble(!(!$('login'))); return (0) };
		
	  toggleInfoBubble(false); // if there are any uploaded images, hide info bubble
	  for (var i = 0; i < allImgs.length; i++) {
		idx = allImgs[i].id.substr(allImgs[i].id.indexOf('_')+1);
        if (usedImgs.indexOf(idx) != -1) {
          allImgs[i].className = 'images_selected';
		  Position.clone(allImgs[i], $('chkimage_'+idx), { setWidth: false, setHeight: false, offsetLeft: 3, offsetTop: 3});
		  
          $('chkimage_'+idx).show();
        } else {
          allImgs[i].className = 'images';
          $('chkimage_'+idx).hide();		  
        }
      }
    }
  });
}

function adjustSliders(im_id, ph_id, css) { // po potrebi skrije sliderje na slikah (glede na odnos razmerja visine in sirine slike ter placeholderja) in prikaze opozorilo o premajhni sliki
	im = $(im_id);
	ph = $('ph_'+ph_id);

	if (!im) { // ce ni nobene slike v placeholderju, potem ne prikazemo nobenega sliderja
      $('v_move_track_'+ph_id).hide();
      $('h_move_track_'+ph_id).hide();
      $('zoom_track_'+ph_id).hide();
      $('text_image_icon_'+ph_id).hide();
	  return true;
	}
    $('text_image_icon_'+ph_id).show();

	// najprej izracunamo, ce je potreben warning za premalo sliko
	min_dpi = 180; // minimalen dpi slike za tisk
	rpwi = 11.2; // prava sirina (natisnjene) strani v inchih
	rphi = 8.1; // prava visina (natisnjene) strani v incih

	page_w = $('work_image').getWidth();
	page_h = $('work_image').getHeight();
	div_w = ph.getWidth();
	div_h = ph.getHeight();	
	img_w = $(im_id+"_w").value;
	img_h = $(im_id+"_h").value;
	scale = css.maximum-css.value+1;

	img_dpi_w = (img_w * page_w) / (rpwi * div_w * scale); // resolucija fotke po sirini
	img_dpi_h = (img_h * page_h) / (rphi * div_h * scale); // resolucija fotke po visini

	if (img_dpi_w < min_dpi || img_dpi_h < min_dpi) { // ce je katera od resolucij manjsa od resolucije tiska, potem prikazemo opozorilo
		$('warning_'+ph_id).show();
	} else {
		$('warning_'+ph_id).hide();
	}
	// konec izracuna za prikaz warninga
	
	if (css && css.maximum-css.value > 0) { // ce zoomiramo v sliko, potem vedno pokazemo oba sliderja
	  $('v_move_track_'+ph_id).show();
	  $('h_move_track_'+ph_id).show();
	  return true;
	}
		
	im_portrait=(im.getHeight() > im.getWidth());
	ph_portrait=(ph.getHeight() > ph.getWidth());
	im_ratio=(im.getWidth()/im.getHeight());
	ph_ratio=(ph.getWidth()/ph.getHeight());
    
    //alert("here");
	if (im_ratio == ph_ratio) { // ce sta tako slika kot placeholder enake orientacije, potem ne prikazemo sliderjev
	  $('v_move_track_'+ph_id).hide();
	  $('h_move_track_'+ph_id).hide();
      $('zoom_track_'+ph_id).show();	  
	  return true;
	} else if (im_ratio < ph_ratio) { // ce je placeholder bolj landscape postavitve in slika bolj portrait
	  $('v_move_track_'+ph_id).show(); // potem vertikalni slider prikazemo, horizontalnega pa ne
	  $('h_move_track_'+ph_id).hide();
      $('zoom_track_'+ph_id).show();	  
	  return true;
	} else if (im_ratio > ph_ratio) { // ce pa je placeholder bolj portrait in slika bolj landscape
	  $('v_move_track_'+ph_id).hide(); // potem horizontalni slider prikazemo, vertikalnega pa ne
	  $('h_move_track_'+ph_id).show();
      $('zoom_track_'+ph_id).show();	  
	  return true;
	}
}

function toggleInfoBubble(visible) {
	bubble = document.getElementById('info_bubble');
	bubble.style.display = (visible) ? 'block' : 'none';
}

function reloadThumb(which) {
    var now = new Date();
	var thumb = $('pp_'+which);
    if (document.images && thumb) {
		thumb.src = thumb.src + '&t=' + now.getTime() + "&rwc=1";
    }
}

function checkClass(oElm, strClassName) {
	strClassName = strClassName.replace(/\-/g, "\\-");
	var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
	return oRegExp.test(oElm.className);
}

var myDraggableObserver = {
	onStart: function(eventName, draggable, event) {
		isDragging = true;
//		if (draggable == myDraggable) {
			//take action (dragging has started)
//		}
	},
			
	onDrag: function(eventName, draggable, event) {
		isDragging = true;
//		if (draggable == myDraggable) {				
			//take action (dragging is going on)	
//		}
	},

	onEnd: function(eventName, draggable, event) {
		isDragging = false;
//		if (draggable == myDraggable) {

			//take action (dragging has stopped)
//		}
	}
}

Draggables.addObserver(this.myDraggableObserver);

RollIt = {
    timeout : new Array(),
    showPopup : function(obj, timeID){
        clearTimeout(this.timeout[timeID]);
        if($(obj).style.display == 'none'){
			for (i=0;i<this.timeout.length;i++) {
				if (i!=timeID && $('mp_'+i)) {
					clearTimeout(this.timeout[i]);
					this.hidePopup($('mp_'+i), i);
				}
			}
            this.timeout[timeID] = setTimeout(function(){new Effect.Appear(obj, {duration:.3, fps:20, to:1})},50);
        }
    },
    hidePopup : function(obj, timeID){
        if($(obj).style.display == 'none'){
            clearTimeout(this.timeout[timeID]);
        }else{
            this.timeout[timeID] = setTimeout(function(){new Effect.Fade(obj, {duration:.3, fps:20})},300);
        }
    },
    cancel : function(timeID) {
    	clearTimeout(this.timeout[timeID]);
    }
}

/* COLOR PICKER */
// Color Picker Script from Flooble.com
// For more information, visit 
//	http://www.flooble.com/scripts/colorpicker.php
// Copyright 2003 Animus Pactum Consulting inc.
// You may use and distribute this code freely, as long as
// you keep this copyright notice and the link to flooble.com
// if you chose to remove them, you must link to the page
// listed above from every web page where you use the color
// picker code.
//---------------------------------------------------------

var perline = 9;
     var divSet = false;
     var curId;
     var colorLevels = Array('0', '3', '6', '9', 'C', 'F');
     var colorArray = Array();
     var ie = false;
     var nocolor = '000000';
	 if (document.all) { ie = true; nocolor = '000000'; }
	 function getObj(id) {
		if (ie) { return document.all[id]; } 
		else {	return document.getElementById(id);	}
	 }

     function addColor(r, g, b) {
     	var red = colorLevels[r];
     	var green = colorLevels[g];
     	var blue = colorLevels[b];
     	addColorValue(red, green, blue);
     }

     function addColorValue(r, g, b) {
     	colorArray[colorArray.length] = r + r + g + g + b + b;
     }
     
     function setColor(color) {
     	var link = getObj(curId);
     	var field = getObj(curId + 'field');
     	var picker = getObj('colorpicker');
     	field.value = color;
     	if (color == '') {
	     	link.style.background = "#"+nocolor;
	     	link.style.color = "#"+nocolor;
	     	color = nocolor;
     	} else {
	     	link.style.background = "#"+color;
	     	link.style.color = "#"+color;
	    }
     	picker.style.display = 'none';
        eval(getObj(curId + 'field').title);
     }
        
     function setDiv() {     
     	if (!document.createElement) { return; }
        var elemDiv = document.createElement('div');
        if (typeof(elemDiv.innerHTML) != 'string') { return; }
        genColors();
        elemDiv.id = 'colorpicker';
	    elemDiv.style.position = 'absolute';
        elemDiv.style.display = 'none';
        elemDiv.style.border = '#000000 1px solid';
        elemDiv.style.background = '#FFFFFF';
        elemDiv.innerHTML = '<div style="font-family:Verdana; font-size:11px;">Barva:<br /> ' 
        	+ getColorTable() 
        	+ '</div>';

        document.body.appendChild(elemDiv);
        divSet = true;
     }
     
     function pickColor(id) {
     	if (!divSet) { setDiv(); }
     	var picker = getObj('colorpicker');     	
		if (id == curId && picker.style.display == 'block') {
			picker.style.display = 'none';
			return;
		}
     	curId = id;
     	var thelink = getObj(id);
     	Position.clone(thelink, picker, { setWidth: false, setHeight: false, offsetLeft: 0, offsetTop: -130});
//      picker.style.top = getAbsoluteOffsetTop(thelink) + 20;
//     	picker.style.left = getAbsoluteOffsetLeft(thelink);     
	    picker.style.zIndex = '200';
        picker.style.display = 'block';
     }
     
     function genColors() {
        addColorValue('0','0','0');
        addColorValue('3','3','3');
        addColorValue('6','6','6');
        addColorValue('8','8','8');
        addColorValue('9','9','9');                
        addColorValue('A','A','A');
        addColorValue('C','C','C');
        addColorValue('E','E','E');
        addColorValue('F','F','F');                                
			
        for (a = 1; a < colorLevels.length; a++)
			addColor(0,0,a);
        for (a = 1; a < colorLevels.length - 1; a++)
			addColor(a,a,5);

        for (a = 1; a < colorLevels.length; a++)
			addColor(0,a,0);
        for (a = 1; a < colorLevels.length - 1; a++)
			addColor(a,5,a);
			
        for (a = 1; a < colorLevels.length; a++)
			addColor(a,0,0);
        for (a = 1; a < colorLevels.length - 1; a++)
			addColor(5,a,a);
			
			
        for (a = 1; a < colorLevels.length; a++)
			addColor(a,a,0);
        for (a = 1; a < colorLevels.length - 1; a++)
			addColor(5,5,a);
			
        for (a = 1; a < colorLevels.length; a++)
			addColor(0,a,a);
        for (a = 1; a < colorLevels.length - 1; a++)
			addColor(a,5,5);

        for (a = 1; a < colorLevels.length; a++)
			addColor(a,0,a);			
        for (a = 1; a < colorLevels.length - 1; a++)
			addColor(5,a,5);
			
       	return colorArray;
     }
     function getColorTable() {
         var colors = colorArray;
      	 var tableCode = '';
         tableCode += '<table border="0" cellspacing="1" cellpadding="1">';
         for (i = 0; i < colors.length; i++) {
              if (i % perline == 0) { tableCode += '<tr>'; }
              tableCode += '<td bgcolor="#000000"><a style="outline: 1px solid #000000; color: #' 
              	  + colors[i] + '; background: #' + colors[i] + ';font-size: 10px;" title="' 
              	  + colors[i] + '" href="javascript:setColor(\'' + colors[i] + '\');">&nbsp;&nbsp;&nbsp;</a></td>';
              if (i % perline == perline - 1) { tableCode += '</tr>'; }
         }
         if (i % perline != 0) { tableCode += '</tr>'; }
         tableCode += '</table>';
      	 return tableCode;
     }
     function relateColor(id, color) {
     	var link = getObj(id);
     	if (color == '') {
	     	link.style.background = "#"+nocolor;
	     	link.style.color = "#"+nocolor;
	     	color = nocolor;
     	} else {
	     	link.style.background = "#"+color;
	     	link.style.color = "#"+color;
	    }
     }

    function getAbsoluteOffsetTop(obj) {
     	var top = obj.offsetTop;
     	var parent = obj.offsetParent;
     	while (parent != document.body) {
     		top += parent.offsetTop;
     		parent = parent.offsetParent;
     	}
     	return top;
     }
     
     function getAbsoluteOffsetLeft(obj) {
     	var left = obj.offsetLeft;
     	var parent = obj.offsetParent;
     	while (parent != document.body) {
     		left += parent.offsetLeft;
     		parent = parent.offsetParent;
     	}
     	return left;
     }

/* END COLOR PICKER */


/* TABS */
/*-----------------------------------------------------------
    Toggles element's display value
    Input: any number of element id's
    Output: none 
    ---------------------------------------------------------*/
function toggleDisp() {
    for (var i=0;i<arguments.length;i++){
        var d = $(arguments[i]);
        if (d.style.display == 'none')
            d.style.display = 'block';
        else
            d.style.display = 'none';
    }
}
/*-----------------------------------------------------------
    Toggles tabs - Closes any open tabs, and then opens current tab
    Input:     1.The number of the current tab
                    2.The number of tabs
                    3.(optional)The number of the tab to leave open
                    4.(optional)Pass in true or false whether or not to animate the open/close of the tabs
    Output: none 
    ---------------------------------------------------------*/
function toggleTab(num,numelems,opennum,animate) {
    if ($('tabContent'+num).style.display == 'none'){
		var bgImgs = $('tabContent'+num).getElementsByTagName('img');
		
		var j = 0;
		for (var i = 0; i < bgImgs.length; i++) {
			imgrel = bgImgs[i].attributes.getNamedItem('rel').value;
			imgsrc = bgImgs[i].src;
			
			if (imgrel != imgsrc) { bgImgs[i].src = imgrel; j++ }
		}
			
        for (var i=1;i<=numelems;i++){
            if ((opennum == null) || (opennum != i)){
                var temph = 'tabHeader'+i;
                var h = $(temph);
                if (!h){
                    var h = $('tabHeaderActive');
                    h.id = temph;
                }
                var tempc = 'tabContent'+i;
                var c = $(tempc);
                if(c.style.display != 'none'){
                    if (animate || typeof animate == 'undefined')
                        Effect.toggle(tempc,'appear',{duration:0.5, queue:{scope:'menus', limit: 3}});
                    else
                        toggleDisp(tempc);
                }
            }
        }
        var h = $('tabHeader'+num);
        if (h)
            h.id = 'tabHeaderActive';
        h.blur();
        var c = $('tabContent'+num);
        c.style.marginTop = '-1px';
        if (animate || typeof animate == 'undefined'){
            Effect.toggle('tabContent'+num,'appear',{duration:0.5, queue:{scope:'menus', position:'end', limit: 3}});
        }else{
            toggleDisp('tabContent'+num);
        }
    }
}
/* END TABS */