﻿// Variables
var SPdomain = getDomain(document.location.href);

var rels = ['lang','root','content','prettyPhoto'];
var langMenu = {count:-1, items:new Array()};
var rootMenu = {count:-1, items:new Array()};
var contentMenu = {count:-1, items:new Array()};
var selLang = "FO";
var selID = "";
var selParentName = "";
var content = "";
var selContentMenu = new Array();
var rels = ['lang','root','content','prettyPhoto'];
var urlQ = getUrlQueries();
var rootFolderArr = (typeof urlQ["RootFolder"] !== "undefined") ? ($.makeArray(unescape(urlQ["RootFolder"]).replace(/^\//g,"").split("/"))) : null ; // RootFolder%3D%252fPages%252flang%252froot%252fchild ~ ['Pages','lang','root','child'] // Use like if(rootFolderArr) ? true : false ;
var imgGal = new Array();

//To do, page select??

$(document).ready(function() {


	if(SPEditMode){
		// if there is a field on the page the we can use the editor, let's do it!
		if($(".ms-formbody").contents("[nodeType=8][nodeValue*='FieldInternalName=\"CMSantBody\"']").length != 0){
			///ckeditor/ckeditor.js
			$.getScript("/ckeditor/ckeditor.js",function(){
		            var domain = getDomain(document.location.href);
		            CKEDITOR.basePath = domain + "/ckeditor/";
		            CKEDITOR.templates_replaceContent = false;
		            CKEDITOR.contentsCss = "/css/style_2010.css";
	        	    CKEDITOR.replace($(".ms-formbody").contents("[nodeType=8][nodeValue*='FieldInternalName=\"CMSantBody\"']").parent().find("textarea").attr("name"), {
			        filebrowserBrowseUrl : '/Images1/Forms/AllItems.aspx'
			    });
			});
			// the rel field autocomplete function will suggest rels
			$rel = $(".ms-formbody").contents("[nodeType=8][nodeValue*='FieldInternalName=\"Rel\"']").parent().find("INPUT");
			if($rel.length > 0 && rootFolderArr.length > 0){ // does field exists then set the 
				if($rel.val() == ""){ //if the value is empty fill it
					switch(parseInt(rootFolderArr.length)){
						case 1:
							$rel.val(rels[0]);
						;
						break
						case 2:
							$rel.val(rels[1]);
						;
						break
						default:
							if(rootFolderArr.length > 2){
								$rel.val(rels[2]);
							};
						;
					}
				}
				
				$rel.autocomplete({
	                minChars: 0,
	                maxHeight: 100,
	                width: 386,
	                deferRequestBy: 0, //miliseconds
	                // callback function:
	                onSelect: function(value, data) { 
	                },
	                // local autosugest options:
	                lookup: rels  //local lookup values
				});	
			};
			// get the level in the folder structure
				
		};
	} // SPEditMode 
	
	
	// when creating a new Web Part Page and the name field is empty, just fill in "default" 
	if(typeof MSOWebPartPageFormName !== "undefined" && $("#onetidListTitle").length > 0 && $("#onetidListTitle").val() == ""){
		$("#onetidListTitle").val("default");
	}
	
	// are we in a opened window and are we looking for pictures?
	if(typeof window.opener !== "undefined"){ //&& (typeof ctx !== "undefined" && ctx.listTemplate == 109)
		// and we have the picture display form page
		if($("#SPFieldFile A").length > 0){
 		   insertUrlToImageMenu();
 		}
	}	


	
	
	if(langMenu.count < 0){
		// load the xml for the languages
		langMenu = getLanguages();
	}
	
	// create language manu items
	$.each(langMenu.items,function(i,x){
		$("#level1 UL:first").append("<li><a href=\'" + x.Name + "\' id=\'"+ x.ID +"\' rel=\'"+ x.Rel +"\' lang=\'"+ x.Name +"\'>"+ x.Title +"</a></li>");
	});

	// add event to clicks
	$('a[rel*=lang]').live('click', function(e) {
		//index console.debug($("LI").index($(this).parent()));
		$('a[rel*=lang]').parent().css("color","");
		$(this).parent().css("color","#dedede"); // to do: toggle the color of the bullet right!
		selLang = $(this).attr("lang");
		content = $.grep(langMenu.items, function(a){ 
		    return ($(a).attr("Name") == selLang);
		});
		// clean 3 level menu
		$("#level3 UL:first").children("LI").remove();
		// set title on document
		document.title = content[0].Title;
		// set content on page
		resetScroll();
		$("#contentDiv").html("<div id=\"innerHTML\">" + content[0].Body.replace("<![CDATA[","").replace("]]>","") + "</div>").show();
		if($("#contentDiv").html().length < 40){
			$("#contentDiv").hide();
		}
		fixScroolContentDiv();
		// slide and set opacity
	//		$("#level4").effect('slide',{},600).opacity(0.92);
		// get the menu below selected language

		getMenuByLanguage(selLang);
			$("#level2 UL:first").children("LI").remove();
			$.each(rootMenu.items,function(i,x){
				$("#level2 UL:first").append("<li><a href=\'" + x.Path.replace(/\d{1,9};#/g, "") + "/" + x.Name + "\' id=\'"+ x.ID +"\' rel=\'"+ x.Rel +"\' lang=\'"+ x.Name +"\'>"+ x.Title +"</a></li>");
			});
     	return false;
	});

	$('a[rel*=root]').live('click', function(e) {
		$("#level3 UL:first").children("LI").remove();
		$('a[rel*=root]').parent().css("color","");
		$(this).parent().css("color","#dedede");
		selContentMenu = new Array();
		selParentName = $(this).attr("lang");
		selID =  $(this).attr("id").toString();
		content = $.grep(rootMenu.items, function(a){ 
		    return ($(a).attr("ID") == selID);
		});
		
		$("#contentDiv").css("filter","alpha(opacity=90)");

		// set title on document
		document.title = content[0].Title;
		// set content on page
		resetScroll();
		$("#contentDiv").html("<div id=\"innerHTML\">" + content[0].Body.replace("<![CDATA[","").replace("]]>","") + "</div>").show();
		if($("#contentDiv").html().length < 40){
			$("#contentDiv").hide();
		}

		fixScroolContentDiv();
		selContentMenu  = $.grep(contentMenu.items, function(a){ 
		   return ($(a).attr("Path").lastIndexOf("/" + selParentName) != -1);
	   });
	   // if we find any menu items below selected parent there are her, ready to serve
	   if(selContentMenu.length > 0){
		     $.each(selContentMenu,function(i,x){
		        $("#level3 UL:first").append("<li><a href=\'" + x.Path.replace(/\d{1,9};#/g, "") + "/" + x.Name + "\' id=\'"+ x.ID +"\' rel=\'"+ x.Rel +"\' lang=\'"+ x.Name +"\'>"+ x.Title +"</a></li>");
		    });
	   }
	   
		// load any picture galleries
				if($("UL[id^=mycarousel]").length > 0){
				jQuery.getScript("/_catalogs/masterpage/CMSant/scripts/CMSantImageSlider.js",function(){
				jQuery.get("/css/map/skin.css",function(e){
							    var elm = jQuery("<style>"+e+"</style>");
							    jQuery(document.body).append(elm);
				
				            $("UL[id^=mycarousel]").each(function(){
				                imgGal = getImagesByPictureLibrary($(this).attr("title"));
				                jQuery(this).jcarousel({
					    		    size: imgGal.length,
					    		    initCallback: mycarousel_initCallback,
					    		    itemLoadCallback: {onBeforeAnimation: mycarousel_itemLoadCallback},
					    		    auto: 0,
					    		    animation: 1500
				    		       });
				    		    //$("a[rel='" + $(this).find("A:first").attr("rel") + "']").prettyPhoto();

				            });
				        });
				    });
				}

	   
		return false;
	});
	
	$('a[rel*=content]').live('click', function(e) {
		imgGal = [];
		$('a[rel*=content]').parent().css("color","");
		$(this).parent().css("color","#dedede");

		selID =  $(this).attr("id").toString();
		
		// hide opacity if in project folder
		if(content[0].Path.indexOf("Verkætlanir",0) > 1){
			$("#contentDiv").css("filter","none");
		}
		content = $.grep(selContentMenu, function(a){ 
		    return ($(a).attr("ID") == selID);
		});

		if(content[0].Body == ""){
			content[0].Body = getContentByFolder(content[0].Path.replace(/\d{1,9};#/g, "/") + "/" + content[0].Name).items[0].Body;
			//Get the content from WS
		}
		// set title on document
		document.title = content[0].Title;
		// set content on page
		resetScroll();

		$("#contentDiv").html("<div id=\"innerHTML\">" + content[0].Body.replace("<![CDATA[","").replace("]]>","") + "</div>").show();
		if($("#contentDiv").html().length < 40){
			$("#contentDiv").hide();
		}

		fixScroolContentDiv();
//		$("#level4").effect('slide',{},600).opacity(0.92);
	//		$("#level4").show().opacity(0.92);
		
		// load any picture galleries
				if($("UL[id^=mycarousel]").length > 0){
				jQuery.getScript("/_catalogs/masterpage/CMSant/scripts/CMSantImageSlider.js",function(){
				jQuery.get("/css/map/skin.css",function(e){
							    var elm = jQuery("<style>"+e+"</style>");
							    jQuery(document.body).append(elm);
				
				            $("UL[id^=mycarousel]").each(function(){
				                imgGal = getImagesByPictureLibrary($(this).attr("title"));
				                //alert(imgGal.length);
									// some bug in Chrome is here
				                    jQuery(this).jcarousel({
					    		    size: imgGal.length,
					    		    initCallback: mycarousel_initCallback,
					    		    itemLoadCallback: {onBeforeAnimation: mycarousel_itemLoadCallback},
					    		    auto: 0,
					    		    animation: 1500
				    		       });
				    		  //  $("a[rel='" + $(this).find("A:first").attr("rel") + "']").prettyPhoto();

				            });
				        });
				    });
				}
		
		
		return false;
	});	
	
	
	$('a[rel^=prettyPhoto]').live('click', function(e) {
		if($(this).attr("href").match(/.*(\.[Jj][Pp][Gg]|\.[Gg][Ii][Ff]|\.[Jj][Pp][Ee][Gg]|\.[Pp][Nn][Gg])/g) != null){
			$.prettyPhoto.open([$(this).attr("href")],[''],['']);
		} else {
			$.prettyPhoto.open(['' + $(this).attr("href") + '/default.aspx?iframe=true&width=100%&height=100%'],[$(this).attr("lang")],['']);
		}
		return false;
	});
	
	$('a[rel=imgBelow]').live('click', function(e) {
	//alert('Nitin');
	if($(this).attr("href").indexOf('youtube.com') == -1)
	{
		if($("#GalPic").length){
//    		$("#GalPic").html("<a href='"+ $(this).attr("href").replace("_w/","").replace("_jpg","") +"' rel='prettyPhoto'><img src='"+ $(this).attr("href") +"' border='0'/></a>");
    		$("#GalPic").html("<img src='"+ $(this).attr("href") +"' width=\"640\" border='0' onmouseover=\"showArrows(this)\" onmouseout=\"hideArrows(this)\"/>");
		} else {
//		    $(".jcarousel-skin-map").closest("DIV").append("<div id='GalPic'><a href='"+ $(this).attr("href").replace("_w/","").replace("_jpg","") +"' rel='prettyPhoto'><img src='"+ $(this).attr("href") +"' border='0'/></a></div>");
		    $(".jcarousel-skin-map").closest("DIV").append("<div id='GalPic'><img src='"+ $(this).attr("href") +"' border='0' width=\"640\" onmouseover=\"showArrows(this)\" onmouseout=\"hideArrows(this)\"/></div>");
		}
		return false;
	}
	else
	{
			if($("#GalPic").length){
//    		$("#GalPic").html("<a href='"+ $(this).attr("href").replace("_w/","").replace("_jpg","") +"' rel='prettyPhoto'><img src='"+ $(this).attr("href") +"' border='0'/></a>");
    		$("#GalPic").html("<iframe class=\"youtube-player\" type=\"text/html\" width=\"640\" height=\"385\" src=\""+ $(this).attr("href") +"\" frameborder=\"0\"></iframe>");
		} else {
//		    $(".jcarousel-skin-map").closest("DIV").append("<div id='GalPic'><a href='"+ $(this).attr("href").replace("_w/","").replace("_jpg","") +"' rel='prettyPhoto'><img src='"+ $(this).attr("href") +"' border='0'/></a></div>");
		    $(".jcarousel-skin-map").closest("DIV").append("<div id='GalPic'><iframe class=\"youtube-player\" type=\"text/html\" width=\"640\" height=\"385\" src=\""+ $(this).attr("href") +"\" frameborder=\"0\"></iframe></div>");
		}
		return false;

	}

	});
});

function showArrows(img){
	//alert("show images");
}

function hideArrows(img){
	//alert("hide images");
}

function resetScroll(){
/*
	if(!$.browser.mozilla){
		$("#contentDiv").height(155);
	}
	$("#contentDiv").css("overflow-y","");
	$("#contentDiv").css("overflow","");
	*/
}

function fixScroolContentDiv(){

	//if($("#contentDiv").height() > 500){ 
		if($.browser.mozilla){
//			$("#contentDiv").height(500).css("overflow","-moz-scrollbars-vertical");
			$("#contentDiv").height($(window).height()).css("overflow","-moz-scrollbars-vertical");
		}
		else
		{
			$("#contentDiv").height($(window).height()).css("overflow-y","auto");
		}
	//}
	
}


//returns items to array
function generateItem(itemData, viewFields){
	var result = {};
	$.each(viewFields, function(idx, field){
		var value = $(itemData).find(field).text();
		if(value == undefined) value = null;
		if(field.indexOf(":") != -1){
			field = field.replace(/:.*/g,"");
		}
		result[field] = value;
	});
	return result;
}

// will return array of objects [Object ID=3 Title=Føroyskt Name=FO Description=-, Object ID=4 Title=English Name=EN Description=-]
function getLanguages(){
	var q = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\
	<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\
	  <soap:Body>\
	    <getLanguages xmlns=\"http://spguy.com/CMSant/\">\
	      <ListName>Pages</ListName>\
	      <ViewName></ViewName>\
	    </getLanguages>\
	  </soap:Body>\
	</soap:Envelope>";
	var result = {count:-1, items:new Array()};
	$.ajax({
		async:false,
		type:"POST",
		url:"/_layouts/CMSantwebservice.asmx",
		contentType:"text/xml; charset=utf-8",
		processData:false,
		data:q.toString(),
		dataType:"xml",
		beforeSend:function(xhr){
			xhr.setRequestHeader('SOAPAction', 'http://spguy.com/CMSant/getLanguages');
		},
		success:function(data){
            	$('LanguageFolder',data).each(function(idx, itemData){
            	result.count++;
                result.items.push(generateItem(itemData,['ID','Title','Name','Description','Body','Rel','Body']));
            });
        }
	});
    return result;
}


function getMenuByLanguage(lang){
	rootMenu = {count:-1, items:new Array()};
	contentMenu = {count:-1, items:new Array()};
	var q = "<?xml version=\"1.0\" encoding=\"utf-8\"?> \
	<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"> \
	  <soap:Body> \
	      <getMenuByLanguage xmlns=\"http://spguy.com/CMSant/\">\
	      <ListName>Pages</ListName>\
	      <LanguagePrefix>"+ lang +"</LanguagePrefix>\
	      <ViewName>All Documents</ViewName>\
	    </getMenuByLanguage>\
	  </soap:Body> \
	</soap:Envelope>";

    $.ajax({
        url: "/_layouts/CMSantwebservice.asmx",
        type: "post",
        dataType: "xml",
        data: q,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("SOAPAction",
            "http://spguy.com/CMSant/getMenuByLanguage");
        },
        contentType: "text/xml; charset=utf-8",
        async: false,
        error: function(XMLHttpRequest, textStatus, errorThrown) {
           // console.debug(errorThrown);
        },
        success: function(data) {
            menuData = data;
            $('RootFolder',data).each(function(idx, itemData){
                rootMenu.count++;
                rootMenu.items.push(generateItem(itemData,['ID:first','Title:first','Name:first','Description:first','Body:first','Rel:first','Path:first']));
            });
            $('ContentFolder',data).each(function(idx, itemData){
                contentMenu.count++;
                contentMenu.items.push(generateItem(itemData,['ID','Title','Name','Description','Body','Rel','Path']));
            });
        }
    });
}


function getContentByFolder(path){
var q = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\
	<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\
	  <soap:Body>\
	    <getContentByFolder xmlns=\"http://spguy.com/CMSant/\">\
      <ListName>Pages</ListName>\
      <FolderRef>" + path + "</FolderRef>\
    </getContentByFolder>\
	  </soap:Body>\
	</soap:Envelope>";
        var result = {count:-1, items:new Array()};
	$.ajax({
		async:false,
		type:"POST",
		url:"/_layouts/CMSantwebservice.asmx",
		contentType:"text/xml; charset=utf-8",
		processData:false,
		data:q.toString(),
		dataType:"xml",
		beforeSend:function(xhr){
			xhr.setRequestHeader('SOAPAction', 'http://spguy.com/CMSant/getContentByFolder');
		},
		success:function(data){
            	$('getContentByFolderResult',data).each(function(idx, itemData){
            	   result.count++;
                   result.items.push(generateItem(itemData,['ID','Title','Name','Description','Body','Rel','Body']));
            });
        }
	});
    return result;
}

function getImagesByPictureLibrary(listName){

var images = new Array();

var q = " \
    <soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>\
<soap:Body> \
   <GetListItems xmlns='http://schemas.microsoft.com/sharepoint/soap/'> \
     <listName>"+listName+"</listName> \
     <viewFields> \
       <ViewFields> \
        <FieldRef Name='Title' /> \
        <FieldRef Name='ID' /> \
		<FieldRef Name='YouTubeID' /> \
		<FieldRef Name='EncodedAbsUrl' /> \
       </ViewFields> \
     </viewFields> \
     </GetListItems> \
  </soap:Body> \
  </soap:Envelope>";
    jQuery.ajax({
          url: "/_vti_bin/lists.asmx",
            type: "POST",
            dataType: "xml",
            data: q,
            async:false,
            complete: function (xData, status) {
			 	$(xData.responseXML).find("[nodeName='z:row']").each(function() {
			 	images.push($(this).attr("ows_YouTubeID") + ',' + unescape($(this).attr("ows_EncodedAbsUrl")))
			 	});
	   		 }
			,
             	error: function(result){
			 	alert(result.responseText);
			 	}
			,
            contentType: "text/xml; charset=\"utf-8\""
    });
//    alert(images.length);
    return images;
}

 function Result(xData, status) {
 	//alert('Hi');
        $(xData.responseXML).find("[nodeName='z:row']").each(function() {
            var liHtml = "<li>" + $(this).attr("ows_YouTubeID") + "</li>";
            //alert(liHtml);
            //$("#MetricsUL").append(liHtml);
        });
    }

function mycarousel_initCallback(carousel)
{
	//	alert('mycarousel_initCallback');
	    jQuery('#mycarousel-prev2').live('click', function() {
	    	//alert(carousel);
	    	console.debug(carousel);
        carousel.scroll(1);
        return false;
    });

}


function mycarousel_itemLoadCallback(carousel, state)
{
	//alert('Loop');
	var randomID = Math.floor(Math.random()*1111);
	//alert(randomID);
	if(state == "init"){
	    for (i = 0; i < imgGal.length; i++) {
	    	//console.debug("Da loop " + i);
	        var item = mycarousel_getItemHTML(imgGal[i],randomID);
	        carousel.add(i,item);
	    }
	    carousel.size(imgGal.length);
    }
};

/**
 * Item html creation helper.
 */
function mycarousel_getItemHTML(item,id)
{
	//alert('Get Item HTML');
    var url_m = getTumbnailsFromFile(item);//.url.replace(/_s.jpg/g, '_m.jpg');
//    alert(url_m[0] + ',' + url_m[1] + ',' + unescape(url_m[2]) + ',' + url_m[3]);
	return '<a href="' + url_m[3] + '" title="' + item + '" rel="imgBelow"><img src="' + unescape(url_m[2]) + '" height="75" border="0" alt="' + item + '" /></a>';
//prettyphoto	return '<a href="' + url_m[3] + '" title="' + item + '"  rel="prettyPhoto['+ id +']"><img src="' + url_m[2] + '" height="75" border="0" alt="' + item + '" /></a>';
};


// get the domain from the url
// getDomain(document.location.href will return http://{domain}
function getDomain(url){
    var d = "";
    try {
        if(L_Menu_BaseUrl.length > 0){
            d = url.substr(0,url.indexOf(location.pathname));
        }
    }
    catch (e) { 
    }
    return d;
}

// /picture/chris.jpg will return chris.jpg
function getFileNameFromString(url){
    var fn = "";
    var arr = new Array();
    try {
        if(url.length > 0){
            arr = escape(url).split("/");
//            fn = url.substr(url.search(/[0-9A-Za-z_ ]+(.[jJ][pP][gG]|.[gG][iI][fF]|.[pP][nN][gG])$/g),url.length); 
//           fn = url.substr(url.search(/[0-9A-Za-z_\[\]]+(.[jJ][pP][gG]|.[gG][iI][fF]|.[pP][nN][gG])$/g),url.length); 
// above does not handle nordic charaters
			fn = arr[arr.length-1];
        }
    }
    catch (e) { 
    }
    return fn;
}

// will return a array ["/ic/chris.jpg", "chris.jpg", "/ic/_t/chris_jpg.jpg", "/ic/_w/chris_jpg.jpg"]
// {"orginal fileLeafRef","file name","thumbnail","middle size img"}
function getTumbnailsFromFile(fileLeafRef){
	var Splitted = fileLeafRef.split(',');
	//alert(Splitted[0]);
	//alert(Splitted[0] + Splitted[1]);
    var a = new Array();
    try {
        var fL = getFileNameFromString(Splitted[1]);
        a.push(Splitted[1]);
        a.push(fL);
        a.push(escape(Splitted[1]).replace(fL,"_t/" + fL.replace(".","_") + ".jpg"));
        if(Splitted[0] == 'undefined')
        {
        	a.push(unescape(Splitted[1]).replace(fL,"_w/" + fL.replace(".","_") + ".jpg"));
        }
        else
        {
        a.push(unescape("http://www.youtube.com/embed/" + Splitted[0]));
        }
    }
    catch (e) { 
    }
    return a;
}

/*
* get url queries
* return: url queries dictionary
*/
function getUrlQueries() {
    var srch = window.location.search;
    if (srch.length > 0) srch = srch.substring(1);
    var sep = srch.split('&');
    var queries = {};
    $.each(sep, function(idx, part) {
        var tmp = part.split('=');
        queries[tmp[0]] = decodeURIComponent(tmp[1]);
    });
    return queries;
}

/*
* go to url which in the ?Source= url query
* defaultTarget: if the source is null, where to go
*/
function goToSource(defaultTarget) {
    var queries = getUrlQueries();
    if (queries['Source'] == undefined) {
        if (defaultTarget != undefined) window.location = defaultTarget;
    } else window.location = queries['Source'];
}


// custom function 
$.fn.opacity = function(_value) {  
    return $(this).css('opacity',_value); 
}; 

function insertUrlToImage(url){
//    $("#69_textInput",window.opener.document).val(url);
    $("input[id$='_textInput']:first",window.opener.document).val(url);
    window.close();
}

function insertUrlToImageMenu(){
	$.MyTumbArr = getTumbnailsFromFile($("#SPFieldFile A").attr("href"));
	var tbl = $("table[id$='toolBarTbl']:first").after("<table class=\"ms-toolbar\" width=\"100%\" cellspacing=\"0\" cellpadding=\"2\" border=\"0\"><tr><td id=\"MyEditorPictureToolBarTbl\"></td></tr></table>");
	$.MyEditorPictureToolBarTbl = $("#MyEditorPictureToolBarTbl");
	$.MyEditorPictureToolBarTbl.append("<a href=\"#\" onclick=\"insertUrlToImage($.MyTumbArr[2]);\">Insert as small picture</a>");
	$.MyEditorPictureToolBarTbl.append(" | "); 
	$.MyEditorPictureToolBarTbl.append("<a href=\"#\" onclick=\"insertUrlToImage($.MyTumbArr[3]);\">Insert as medium picture</a>"); 
	$.MyEditorPictureToolBarTbl.append(" | "); 
	$.MyEditorPictureToolBarTbl.append("<a href=\"#\" onclick=\"insertUrlToImage($.MyTumbArr[0]);\">Insert as full size picture</a>"); 
}



/*
* get url queries
* return: url queries dictionary
*/
function getUrlQueries() {
    var srch = window.location.search;
    if (srch.length > 0) srch = srch.substring(1);
    var sep = srch.split('&');
    var queries = {};
    $.each(sep, function(idx, part) {
        var tmp = part.split('=');
        queries[tmp[0]] = decodeURIComponent(tmp[1]);
    });
    return queries;
}



//autocomplete
/*
*  Ajax Autocomplete for jQuery, version 1.0.6
*  (c) 2009 Tomas Kirda
*
*  Ajax Autocomplete for jQuery is freely distributable under the terms of an MIT-style license.
*  For details, see the web site: http://www.devbridge.com/projects/autocomplete/jquery/
*
*  Last Review: 4/24/2009
*/

(function($) {

    $.fn.autocomplete = function(options) {
        return this.each(function() {
            return new Autocomplete(this, options);
        });
    };

    var reEscape = new RegExp('(\\' + ['/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\'].join('|\\') + ')', 'g');

    var fnFormatResult = function(value, data, currentValue) {
        var pattern = '(' + currentValue.replace(reEscape, '\\$1') + ')';
        return value.replace(new RegExp(pattern, 'gi'), '<strong>$1<\/strong>');
    };

    var Autocomplete = function(el, options) {
        this.el = $(el);
        this.el.attr('autocomplete', 'off');
        this.suggestions = [];
        this.data = [];
        this.badQueries = [];
        this.selectedIndex = -1;
        this.currentValue = this.el.val();
        this.intervalId = 0;
        this.cachedResponse = [];
        this.onChangeInterval = null;
        this.ignoreValueChange = false;
        this.serviceUrl = options.serviceUrl;
        this.isLocal = false;
        this.options = {
            autoSubmit: false,
            minChars: 1,
            maxHeight: 300,
            deferRequestBy: 0,
            width: 0,
            highlight: true,
            params: {},
            fnFormatResult: fnFormatResult,
            delimiter: null
        };
        if (options) { $.extend(this.options, options); }
        if (this.options.lookup) {
            this.isLocal = true;
            if ($.isArray(this.options.lookup)) { this.options.lookup = { suggestions: this.options.lookup, data: [] }; }
        }
        this.initialize();
    };

    Autocomplete.prototype = {

        killerFn: null,

        initialize: function() {

            var me, zindex;
            me = this;

            zindex = Math.max.apply(null, $.map($('body > *'), function(e, n) { var pos = $(e).css('position'); if (pos === 'absolute' || pos === 'relative') { return parseInt($(e).css('z-index'), 10) || 1; } }));

            this.killerFn = function(e) {
                if ($(e.target).parents('.autocomplete').size() === 0) {
                    me.killSuggestions();
                    me.disableKillerFn();
                }
            };

            var uid = new Date().getTime();
            var autocompleteElId = 'Autocomplete_' + uid;

            if (!this.options.width) { this.options.width = this.el.width(); }
            this.mainContainerId = 'AutocompleteContainter_' + uid;

            $('<div id="' + this.mainContainerId + '" style="position:absolute;z-index:' + zindex + '"><div class="autocomplete-w1"><div class="autocomplete" id="' + autocompleteElId + '" style="display:none; width:' + this.options.width + 'px;"></div></div></div>').appendTo('body');

            this.container = $('#' + autocompleteElId);
            this.fixPosition();
            if (window.opera) {
                this.el.keypress(function(e) { me.onKeyPress(e); });
            } else {
                this.el.keydown(function(e) { me.onKeyPress(e); });
            }
            this.el.keyup(function(e) { me.onKeyUp(e); });
            this.el.blur(function() { me.enableKillerFn(); });
            this.el.focus(function() { me.fixPosition(); });

            this.container.css({ maxHeight: this.options.maxHeight + 'px' });
        },

        fixPosition: function() {
            var offset = this.el.offset();
            $('#' + this.mainContainerId).css({ top: (offset.top + this.el.innerHeight()) + 'px', left: offset.left + 'px' });
        },

        enableKillerFn: function() {
            var me = this;
            $(document).bind('click', me.killerFn);
        },

        disableKillerFn: function() {
            var me = this;
            $(document).unbind('click', me.killerFn);
        },

        killSuggestions: function() {
            var me = this;
            this.stopKillSuggestions();
            this.intervalId = window.setInterval(function() { me.hide(); me.stopKillSuggestions(); }, 300);
        },

        stopKillSuggestions: function() {
            window.clearInterval(this.intervalId);
        },

        onKeyPress: function(e) {
            if (!this.enabled) { return; }
            // return will exit the function
            // and event will not fire
            switch (e.keyCode) {
                case 27: //Event.KEY_ESC:
                    this.el.val(this.currentValue);
                    this.hide();
                    break;
                case 9: //Event.KEY_TAB:
                case 13: //Event.KEY_RETURN:
                    if (this.selectedIndex === -1) {
                        this.hide();
                        return;
                    }
                    this.select(this.selectedIndex);
                    if (e.keyCode === 9/* Event.KEY_TAB */) { return; }
                    break;
                case 38: //Event.KEY_UP:
                    this.moveUp();
                    break;
                case 40: //Event.KEY_DOWN:
                    this.moveDown();
                    break;
                default:
                    return;
            }
            e.stopImmediatePropagation();
            e.preventDefault();
        },

        onKeyUp: function(e) {
            switch (e.keyCode) {
                case 38: //Event.KEY_UP:
                case 40: //Event.KEY_DOWN:
                    return;
            }
            clearInterval(this.onChangeInterval);
            if (this.currentValue !== this.el.val()) {
                if (this.options.deferRequestBy > 0) {
                    // Defer lookup in case when value changes very quickly:
                    var me = this;
                    this.onChangeInterval = setInterval(function() { me.onValueChange(); }, this.options.deferRequestBy);
                } else {
                    this.onValueChange();
                }
            }
        },

        onValueChange: function() {
            clearInterval(this.onChangeInterval);
            this.currentValue = this.el.val();
            var q = this.getQuery(this.currentValue);
            this.selectedIndex = -1;
            if (this.ignoreValueChange) {
                this.ignoreValueChange = false;
                return;
            }
            if (q === '' || q.length < this.options.minChars) {
                this.hide();
            } else {
                this.getSuggestions(q);
            }
        },

        getQuery: function(val) {
            var d, arr;
            d = this.options.delimiter;
            if (!d) { return $.trim(val); }
            arr = val.split(d);
            return $.trim(arr[arr.length - 1]);
        },

        getSuggestionsLocal: function(q) {
            var ret, arr, len, val;
            arr = this.options.lookup;
            len = arr.suggestions.length;
            ret = { suggestions: [], data: [] };
            for (var i = 0; i < len; i++) {
                val = arr.suggestions[i];
                if (val.toLowerCase().indexOf(q.toLowerCase()) === 0) {
                    ret.suggestions.push(val);
                    ret.data.push(arr.data[i]);
                }
            }
            return ret;
        },

        getSuggestions: function(q) {
            var cr, me, ls;
            cr = this.isLocal ? this.getSuggestionsLocal(q) : this.cachedResponse[q];
            if (cr && $.isArray(cr.suggestions)) {
                this.suggestions = cr.suggestions;
                this.data = cr.data;
                this.suggest();
            } else if (!this.isBadQuery(q)) {
                me = this;
                me.options.params.query = q;
                $.get(this.serviceUrl, me.options.params, function(txt) { me.processResponse(txt); }, 'text');
            }
        },

        isBadQuery: function(q) {
            var i = this.badQueries.length;
            while (i--) {
                if (q.indexOf(this.badQueries[i]) === 0) { return true; }
            }
            return false;
        },

        hide: function() {
            this.enabled = false;
            this.selectedIndex = -1;
            this.container.hide();
        },

        suggest: function() {
            if (this.suggestions.length === 0) {
                this.hide();
                return;
            }

            var me, len, div, f;
            me = this;
            len = this.suggestions.length;
            f = this.options.fnFormatResult;
            v = this.getQuery(this.currentValue);
            this.container.hide().empty();
            for (var i = 0; i < len; i++) {
                div = $((me.selectedIndex === i ? '<div class="selected"' : '<div') + ' title="' + this.suggestions[i] + '">' + f(this.suggestions[i], this.data[i], v) + '</div>');
                div.mouseover((function(xi) { return function() { me.activate(xi); }; })(i));
                div.click((function(xi) { return function() { me.select(xi); }; })(i));
                //console.log(div);
                this.container.append(div);
            }
            this.enabled = true;
            this.container.show();
        },

        processResponse: function(text) {
            var response;
            try {
                response = eval('(' + text + ')');
            } catch (err) { return; }
            if (!$.isArray(response.data)) { response.data = []; }
            this.suggestions = response.suggestions;
            this.data = response.data;
            this.cachedResponse[response.query] = response;
            if (response.suggestions.length === 0) { this.badQueries.push(response.query); }
            if (response.query === this.getQuery(this.currentValue)) { this.suggest(); }
        },

        activate: function(index) {
            var divs = this.container.children();
            var activeItem;
            // Clear previous selection:
            if (this.selectedIndex !== -1 && divs.length > this.selectedIndex) {
                $(divs.get(this.selectedIndex)).attr('class', '');
            }
            this.selectedIndex = index;
            if (this.selectedIndex !== -1 && divs.length > this.selectedIndex) {
                activeItem = divs.get(this.selectedIndex);
                $(activeItem).attr('class', 'selected');
            }
            return activeItem;
        },

        deactivate: function(div, index) {
            div.className = '';
            if (this.selectedIndex === index) { this.selectedIndex = -1; }
        },

        select: function(i) {
            var selectedValue = this.suggestions[i];
            if (selectedValue) {
                this.el.val(selectedValue);
                if (this.options.autoSubmit) {
                    var f = this.el.parents('form');
                    if (f.length > 0) { f.get(0).submit(); }
                }
                this.ignoreValueChange = true;
                this.hide();
                this.onSelect(i);
            }
        },

        moveUp: function() {
            if (this.selectedIndex === -1) { return; }
            if (this.selectedIndex === 0) {
                this.container.children().get(0).className = '';
                this.selectedIndex = -1;
                this.el.val(this.currentValue);
                return;
            }
            this.adjustScroll(this.selectedIndex - 1);
        },

        moveDown: function() {
            if (this.selectedIndex === (this.suggestions.length - 1)) { return; }
            this.adjustScroll(this.selectedIndex + 1);
        },

        adjustScroll: function(i) {
            var activeItem, offsetTop, upperBound, lowerBound;
            activeItem = this.activate(i);
            offsetTop = activeItem.offsetTop;
            upperBound = this.container.scrollTop();
            lowerBound = upperBound + this.options.maxHeight - 25;
            if (offsetTop < upperBound) {
                this.container.scrollTop(offsetTop);
            } else if (offsetTop > lowerBound) {
                this.container.scrollTop(offsetTop - this.options.maxHeight + 25);
            }
            //this.el.val(this.suggestions[i]);
        },

        onSelect: function(i) {
            var me, onSelect, getValue, s, d;
            me = this;
            onSelect = me.options.onSelect;
            getValue = function(value) {
                var del, currVal;
                del = me.options.delimiter;
                currVal = me.currentValue;
                if (!del) { return value; }
                var arr = currVal.split(del);
                if (arr.length === 1) { return value; }
                return currVal.substr(0, currVal.length - arr[arr.length - 1].length) + value;
            };
            s = me.suggestions[i];
            d = me.data[i];
            me.el.val(getValue(s));
            if ($.isFunction(onSelect)) { onSelect(s, d); }
        }

    };

})(jQuery);









