//Xerias (google maps)
var defaultZoom = 0;
var center;

function displayDialog(url){
 $("#dialog_outer").load(url).dialog({
			title: "My First AJAX dialog",
			modal: true,
			resizable: true	});
}

function displayTextSlotEditDialog(slotName, slotId, technicalName){
	var page = "/comPage/ajTextSlotEditDialog.html?slotId=" + slotId + '&technical_name=' + technicalName;
	//$.fn.colorbox({href: page});
	$.fn.colorbox({href: page, open: true, width:800, height:700});
}

function onSlotActionListOpen(slotId){
    alert(slotId);
    
    $(slotId).unbind('click').click(function(){ 
					var area = $(this).parents('.a-area');
					area.toggleClass('add-slot-now');
					$(document).click(function(e){
                        alert("click");
						var target = e.target, // e.target grabs the node that triggered the event.
						$target = $(target);  // wraps the node in a jQuery object
							if (target.id !== 'a-add-slot-<?php echo $pageid.'-'.$name ?>') {
								area.removeClass('add-slot-now');
							}
					});
				});			
}
function onProductDialogProductReferenceChange(){
			
	search = $("#customer_order_item_product_reference").val();
	$.ajax(
	{
		type: "GET",
		url: "/pmProduct/ajProductReferenceSearch.html",
		data: "search=" + search,
		success: function(message)
		{
			$("#aj_customer_order_product_result").empty();
				if (message.length > 0)
			{							
				$("#aj_customer_order_product_result").append(message);
			}
		}
	});}


function onProductBrowserSearchRequest() { 
		var id = $("#brand_id option:selected").val();
		var name = $("#name").val();
		var url = '/pmProduct/ajProductBrowserSearch.html?brand_id=' + id + '&name=' + name;
		if(id > 0 || name != ''){
			$.ajax({
				url: url,
				success: function(data) {
					$('#searchResults').html(data);}
			});
		}
}
function onProductBrowserResultClick(productReference){
	$("#customer_order_item_product_reference").val(productReference);
	$("#customer_order_item_product_search").hide();
	$("#customer_order_item_overview").show();
	onProductDialogProductReferenceChange();
	}

function swfUploadEventUploadComplete(file){
	location.reload(true);
}


function sidebarClick(id){
	
	if(defaultZoom == 0){
		defaultZoom = map.getZoom();
		center = map.getCenter();
	}
	
	map.setCenter(new GLatLng(markers[id].lattitude, markers[id].longtitude), 15);
	
}
function sidebarHoover(id){
	
	if(defaultZoom == 0){
		defaultZoom = map.getZoom();
		center = map.getCenter();
	}
	
	map.setZoom(defaultZoom);
	map.setCenter(center);
	GEvent.trigger(markers[id], "click");
}
// TinyMCE

var activatedAreas = new Array();

function setTextareaToTinyMCE(sEditorID)
{
  var oEditor = document.getElementById(sEditorID);
    if(oEditor)
  {
    if(activatedAreas[sEditorID] == true)
      unsetTextareaToTinyMCE(sEditorID);
    try {
      activatedAreas[sEditorID] = true;
      tinyMCE.execCommand("mceAddControl", true, sEditorID);
    }
    catch(e)
    {
      alert("Error activating element " + sEditorID + "\n" + e);
    }
  }
}

function unsetTextareaToTinyMCE(sEditorID)
{
  var oEditor = document.getElementById(sEditorID);
  if(oEditor && (activatedAreas[sEditorID] == true))
  {
    try
    {
      tinyMCE.execCommand("mceRemoveControl", true, sEditorID);
      activatedAreas[sEditorID] = false;
    }
    catch(e)
    {
      alert("Error deactivating element " + sEditorID + "\n" + e);
    }
  }
}

function tinymceDeactivate()
{
  try {
    tinyMCE.triggerSave(true,true);
  }
  catch(e)
  {
    alert("Error saving form\n" + e);
  }

  for(var i in activatedAreas)
  {
    if(activatedAreas[i] == true)
    {
      unsetTextareaToTinyMCE(i);
    }
  }
}

function submitForm(formId)
{
 if($(formId).onsubmit())
 {
    $(formId).submit();
 }
}

tinyMCE.init({
  theme : "advanced",
  language : "nl",
  mode : "exact",
  relative_urls : false,
  debug : false,
  valid_elements : "*[*]",
  height:"100%",
  width:"100%",
  theme_advanced_resize_horizontal : false,
  theme_advanced_resizing : true,
  auto_reset_designmode : true
});

function mycarousel_initCallback(carousel)
{
    // Disable autoscrolling if the user clicks the prev or next button.
    carousel.buttonNext.bind('click', function() {
        carousel.startAuto(0);
    });

    carousel.buttonPrev.bind('click', function() {
        carousel.startAuto(0);
    });

    // Pause autoscrolling if the user moves with the cursor over the clip.
    carousel.clip.hover(function() {
        carousel.stopAuto();
    }, function() {
        carousel.startAuto();
    });
};

function sfMediaLibrary_Engine()
{
  // Browser check
  var ua = navigator.userAgent;
  this.isMSIE = (navigator.appName == "Microsoft Internet Explorer");
  this.isMSIE5 = this.isMSIE && (ua.indexOf('MSIE 5') != -1);
  this.isMSIE5_0 = this.isMSIE && (ua.indexOf('MSIE 5.0') != -1);
  this.isGecko = ua.indexOf('Gecko') != -1;
  this.isSafari = ua.indexOf('Safari') != -1;
  this.isOpera = ua.indexOf('Opera') != -1;
  this.isMac = ua.indexOf('Mac') != -1;
  this.isNS7 = ua.indexOf('Netscape/7') != -1;
  this.isNS71 = ua.indexOf('Netscape/7.1') != -1;
  this.isTinyMCE = false;

  // Fake MSIE on Opera and if Opera fakes IE, Gecko or Safari cancel those
  if (this.isOpera) {
    this.isMSIE = true;
    this.isGecko = false;
    this.isSafari =  false;
  }
}

sfMediaLibrary_Engine.prototype = {
  init : function(url)
  {
    this.url = url;
  },
  
  fileBrowserReturn : function (url,PopUp)
  {
	if (PopUp)
	{
		var win =PopUp.getWindowArg("window");
		var input=PopUp.getWindowArg("input");
		win.document.getElementById(input).value=url;
		if (this.fileBrowserType == 'image')      		
		{ 
			if (win.ImageDialog.showPreviewImage)
			{
        			win.ImageDialog.showPreviewImage(url);
			}		
		}
	    PopUp.close();
	}
	else
	{
    		this.fileBrowserWin.document.forms[this.fileBrowserFormName].elements[this.fileBrowserFieldName].value = url;

	} 
  },
  fileBrowserCallBack : function (field_name, url, type, win)
  {
	//Set TinyMCE to true
	this.isTinyMCE=true;
    //Store the URL
	var url = this.url;
 this.fileBrowserType = type;
    //Check the type of image
    if (type == 'image')
      url += '/images_only/1';
    tinyMCE.activeEditor.windowManager.open({ 
    	file: url,
    	title: "Please select a image",
    	width: 640,
    	height: 480,
    	resizable: "yes",
    	inline:    "yes",
    	scrollbars: "yes",
    	close_previous: "yes"
    	}
    , {
        window : win,
        input : field_name,
        mediaLibrary: this
    });
  },

  openWindow : function(options)
  {
    var width, height, x, y, resizable, scrollbars, url;

    if (!options)
      return;
    if (!options['field_name'])
      return;
    if (!options['url'] && !this.url)
      return;
    this.fileBrowserWin = self;
    this.fileBrowserFormName = (options['form_name'] == '') ? 0 : options['form_name'];
    this.fileBrowserFieldName = options['field_name'];
    this.fileBrowserType = options['type'];

    url = this.url;
    if (options['type'] == 'image')
      url += '/images_only/1';

    if (!(width = parseInt(options['width'])))
      width = 550;

    if (!(width = parseInt(options['width'])))
      width = 550;

    if (!(height = parseInt(options['height'])))
      height = 600;

    // Add to height in M$ due to SP2 WHY DON'T YOU GUYS IMPLEMENT innerWidth of windows!!
    if (sfMediaLibrary.isMSIE)
      height += 40;
    else
      height += 20;

    x = parseInt(screen.width / 2.0) - (width / 2.0);
    y = parseInt(screen.height / 2.0) - (height / 2.0);

    resizable = (options && options['resizable']) ? options['resizable'] : "no";
    scrollbars = (options && options['scrollbars']) ? options['scrollbars'] : "no";

    var modal = (resizable == "yes") ? "no" : "yes";

    if (sfMediaLibrary.isGecko && sfMediaLibrary.isMac)
      modal = "no";

    if (options['close_previous'] != "no")
      try {sfMediaLibrary.lastWindow.close();} catch (ex) {}

    var win = window.open(url, "sfPopup" + new Date().getTime(), "top=" + y + ",left=" + x + ",scrollbars=" + scrollbars + ",dialog=" + modal + ",minimizable=" + resizable + ",modal=" + modal + ",width=" + width + ",height=" + height + ",resizable=" + resizable);

    if (options['close_previous'] != "no")
      sfMediaLibrary.lastWindow = win;

    eval('try { win.resizeTo(width, height); } catch(e) { }');

    // Make it bigger if statusbar is forced
    if (sfMediaLibrary.isGecko)
    {
      if (win.document.defaultView.statusbar.visible)
        win.resizeBy(0, sfMediaLibrary.isMac ? 10 : 24);
    }

    win.focus();

  }
}
var SfMediaLibrary = sfMediaLibrary_Engine; // Compatiblity with gzip compressors
var sfMediaLibrary = new sfMediaLibrary_Engine();


//Sliding login panel
$(document).ready(function() {

	// Expand Panel
	$("#open").click(function(){
		$("div#panel").slideDown("slow");
	});

	// Collapse Panel
	$("#close").click(function(){
		$("div#panel").slideUp("slow");
	});

	// Switch buttons from "Log In | Register" to "Close Panel" on click
	$("#toggle a").click(function () {
		$("#toggle a").toggle();
	});

});

//Type watch
(function(jQuery) {
	jQuery.fn.typeWatch = function(o){
		// Options
		var options = jQuery.extend({
			wait : 750,
			callback : function() { },
			highlight : true,
			captureLength : 2
		}, o);
			
		function checkElement(timer, override) {
			var elTxt = jQuery(timer.el).val();
		
			// Fire if text > options.captureLength AND text != saved txt OR if override AND text > options.captureLength
			if ((elTxt.length > options.captureLength && elTxt.toUpperCase() != timer.text) 
			|| (override && elTxt.length > options.captureLength)) {
				timer.text = elTxt.toUpperCase();
				timer.cb(elTxt);
			}
		};
		
		function watchElement(elem) {			
			// Must be text or textarea
			if (elem.type.toUpperCase() == "TEXT" || elem.nodeName.toUpperCase() == "TEXTAREA") {

				// Allocate timer element
				var timer = {
					timer : null, 
					text : jQuery(elem).val().toUpperCase(),
					cb : options.callback, 
					el : elem, 
					wait : options.wait
				};

				// Set focus action (highlight)
				if (options.highlight) {
					jQuery(elem).focus(
						function() {
							this.select();
						});
				}

				// Key watcher / clear and reset the timer
				var startWatch = function(evt) {
					var timerWait = timer.wait;
					var overrideBool = false;
					
					if (evt.keyCode == 13 && this.type.toUpperCase() == "TEXT") {
						timerWait = 1;
						overrideBool = true;
					}
					
					var timerCallbackFx = function()
					{
						checkElement(timer, overrideBool)
					}
					
					// Clear timer					
					clearTimeout(timer.timer);
					timer.timer = setTimeout(timerCallbackFx, timerWait);				
										
				};
				
				jQuery(elem).keydown(startWatch);
			}
		};
		
		// Watch Each Element
		return this.each(function(index){
			watchElement(this);
		});
		
	};

})(jQuery);

