﻿/// <reference name="MicrosoftAjax.debug.js" />
/// <reference name="MicrosoftAjaxTimer.debug.js" />
/// <reference name="MicrosoftAjaxWebForms.debug.js" />
/// <reference name="AjaxControlToolkit.ExtenderBase.BaseScripts.js" assembly="AjaxControlToolkit" />
/// <reference name="AjaxControlToolkit.Common.Common.js" assembly="AjaxControlToolkit" />

//////////////////////Widget logic////////////////////////

function WidgetPositionChanged(sender, args){
    var next = args.find_Next();
    if (next == null)
        next = ""; //Set next as empty
    else 
        next = next.get_Tag(); //The tag contains the ID of the service
       Website.Proxy.WidgetMoved(args.get_DragSource().get_Tag(), args.get_DropZone().get_Tag(), next);
}

function CanDrop(dragSource, dropTarget){
    //If this is the current active tab, then we cant drop
    if (Sys.UI.DomElement.containsCssClass(dropTarget.get_element(), 'selected'))
        return false;
    //Check if the dragsource is a group
    var retval = true;
    Array.forEach(Sys.Application.getComponents(), function(i){ //Loop over each component
        var type = Object.getType(i);
        //Check if the type of the component is a dropTargetBehavior (which always is a group)
        if (type == Infocaster.Web.Ajax.DropTargetBehavior){
            //If the tag of the item is the same as the tag of the dragsource, we know that the dragsource is a group
            if (i.get_Tag() == dragSource.get_Tag()){
            	retval = false;     
            }
        }
    });
    return retval;
}

function WidgetGroupDropped(sender, args){
    if (CanDrop(args.get_DragSource(), args.get_DropZone())){
        Website.Proxy.WidgetGroupDropped(args.get_DragSource().get_Tag(), sender.get_Tag());        
        //Remove the element from the screen
        $common.removeElement(args.get_DragSource().get_element());
        //Also remove the dragsource component because else conflicts will arise
        Sys.Application.removeComponent(args.get_DragSource()); 
    }
}

function WidgetGroupEnter(sender, args){
    if (CanDrop(args.get_DragSource(), args.get_DropZone())){
        $common.setElementOpacity(args.get_DragSource().get_element(),0.5);
    }
}

function WidgetGroupLeave(sender, args){
    if (CanDrop(args.get_DragSource(), args.get_DropZone())){
        $common.setElementOpacity(args.get_DragSource().get_element(),1);
    }
}

function WidgetCloseClicked(container, service){
    var c = confirm("Weet je zeker dat je deze widget wilt verwijderen?");
    if (c){
        Array.forEach(Sys.Application.getComponents(), function(i){
            var type = Object.getType(i);
            //If its either the tab or the dragSourceBehaviour
            if (type == Infocaster.Web.Ajax.DropTargetBehavior || type == Infocaster.Web.Ajax.DragSourceBehavior){
                if (i.get_Tag() == service){
                    var el = i.get_element();
                    //Small hack for the tab panel since there is a splitter div next to the button which divides the tab buttons, remove this to
                    if (type == Infocaster.Web.Ajax.DropTargetBehavior)
                        el = el.parentNode;
                    //Remove the element itself
                    $common.removeElement(el);
                    //Remove the component
                    Sys.Application.removeComponent(i);                 
                }    
            }
        });
        //Update server
        Website.Proxy.WidgetClosed(service);
    }
}
function WidgetMinimizedChanged(service, collapser){
    //Since this event is called before the collapser, the actual value is the exact oposite of the one known by the collapser
    var collapsed = !collapser.get_Collapsed();
    Website.Proxy.WidgetCollapsedChanged(service, collapsed);
}

//////////////////////Feed logic////////////////////////
//Called when the mouse starts hovering over a feed item
function RegisterFeedItem(sender, data){
    var descriptionBoxExtender = $find('DescriptionBoxExtender');
    if (descriptionBoxExtender != null){
        descriptionBoxExtender.bind(sender, true);
        var el = descriptionBoxExtender.get_element();
        $get("description_title", el).innerHTML = sender.innerHTML;
        $get("description_message", el).innerHTML = data.Description;
        if (data.Source != null)
        	$get("description_subtitle", el).innerHTML = "Bron: " + data.SourceTitle + " om " + data.Date + "<br />";
        else
        	$get("description_subtitle", el).innerHTML = "";
        if (data.TotalParticles != null)
        	$get("description_subtitle", el).innerHTML += "Aantal meningen: " + data.TotalParticles;
    }
}

//Call to show a MouseOver
function BindMouseover(sender, message, errorX, errorY, alignRight){
    var mouseOverExtender = $find('MouseOverPopup');
    if (mouseOverExtender != null) {
		
    	var docBounds = $common.getBounds(window.document.documentElement);
    	var bounds = $common.getBounds(sender);
    	var padding = $common.getPaddingBox(sender);
    	if (bounds.x + bounds.width + 200 > docBounds.width)
    		alignRight = true;
    	var loc = new Sys.UI.Point(bounds.x + bounds.width - padding.right + errorX, bounds.y - bounds.height + errorY);
    	
		if(alignRight == "False")
		{
			var el = $get('mouseover_body', mouseOverExtender.get_element());
			$get('mouseover_right', mouseOverExtender.get_element()).style.display = "none";
			$get('mouseover_left', mouseOverExtender.get_element()).style.display = "inline";
		}
		else
		{
			var el = $get('mouseover_body2', mouseOverExtender.get_element());
			$get('mouseover_left', mouseOverExtender.get_element()).style.display = "none";
			$get('mouseover_right', mouseOverExtender.get_element()).style.display = "inline";
			loc.x = bounds.x - 100;
		}
		el.innerHTML = decodeURI(message);
        mouseOverExtender.bind(sender, true);
        mouseOverExtender.set_Location(loc);
    }
}

//UWA MessageMap
if (typeof UWA == 'undefined') UWA = {};
UWA.MessageHandler = function(message) {
  var id = message.id;
  switch (message.action) {
    case 'resizeHeight':
      var frame = document.getElementById('frame_' + id);
      if (frame) {
        frame.setAttribute('height', message.value);
      }
      break;
   default:
      Sys.Debug.trace(message.action + ': not implemented - ' + message.name + ':' + message.value);
      break;
  }
};

// Textbox default text
function clearDefault(el)
{
	if (el.defaultValue == el.value)
	el.value = "";
}

function undoClearDefault(el)
{
	if(el.value == "")
	el.value = el.defaultValue;
}

function refreshPreviewTitle(source, target)
{
	var text = source.value;
	var targetEl = $get(target);
	targetEl.innerHTML = text;
}

//Shows a certain warning using a messagebox untill the pageloaded event is executed again or the user closes the dialog
function ShowWarning(title, text){
    var ext = $find('MessageBoxExtender');
    if (ext != null) {
        if (Sys.Browser.agent == Sys.Browser.Firefox) {
            $get('MessageBoxTitle').textContent = title;
            $get('MessageBoxText').textContent = text;
        }
        else {
            $get('MessageBoxTitle').innerText = title;
            $get('MessageBoxText').innerText = text;
        }
        ext.show();
        return true;
    }
    return false;
}
Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(function(){
    var ext = $find('MessageBoxExtender');
    if (ext != null)
        ext.hide();
});

//Tries to locate the certain dialog and when found, opens it
function OpenDialog(dialog) {
    var c = $find(dialog);
    if (c != null)
        c.show();
    return false;
}
//Tries to locate the certain dialog and when found, hides it when opened
function CloseDialog(dialog) {
    var c = $find(dialog);
    if (c != null)
        c.hide();
    return false;
}

if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();
// IE5.5+ PNG Alpha Fix v2.0 Alpha: Background Tiling Support
// (c) 2008 Angus Turnbull http://www.twinhelix.com

// This is licensed under the GNU LGPL, version 2.1 or later.
// For details, see: http://creativecommons.org/licenses/LGPL/2.1/

var IEPNGFix = window.IEPNGFix || {};

IEPNGFix.tileBG = function(elm, pngSrc, ready) {
	// Params: A reference to a DOM element, the PNG src file pathname, and a
	// hidden "ready-to-run" passed when called back after image preloading.

	var data = this.data[elm.uniqueID],
		elmW = Math.max(elm.clientWidth, elm.scrollWidth),
		elmH = Math.max(elm.clientHeight, elm.scrollHeight),
		bgX = elm.currentStyle.backgroundPositionX,
		bgY = elm.currentStyle.backgroundPositionY,
		bgR = elm.currentStyle.backgroundRepeat;

	// Cache of DIVs created per element, and image preloader/data.
	if (!data.tiles) {
		data.tiles = {
			elm: elm,
			src: '',
			cache: [],
			img: new Image(),
			old: {}
		};
	}
	var tiles = data.tiles,
		pngW = tiles.img.width,
		pngH = tiles.img.height;

	if (pngSrc) {
		if (!ready && pngSrc != tiles.src) {
			// New image? Preload it with a callback to detect dimensions.
			tiles.img.onload = function() {
				this.onload = null;
				IEPNGFix.tileBG(elm, pngSrc, 1);
			};
			return tiles.img.src = pngSrc;
		}
	} else {
		// No image?
		if (tiles.src) ready = 1;
		pngW = pngH = 0;
	}
	tiles.src = pngSrc;

	if (!ready && elmW == tiles.old.w && elmH == tiles.old.h &&
		bgX == tiles.old.x && bgY == tiles.old.y && bgR == tiles.old.r) {
		return;
	}

	// Convert English and percentage positions to pixels.
	var pos = {
			top: '0%',
			left: '0%',
			center: '50%',
			bottom: '100%',
			right: '100%'
		},
		x,
		y,
		pc;
	x = pos[bgX] || bgX;
	y = pos[bgY] || bgY;
	if (pc = x.match(/(\d+)%/)) {
		x = Math.round((elmW - pngW) * (parseInt(pc[1]) / 100));
	}
	if (pc = y.match(/(\d+)%/)) {
		y = Math.round((elmH - pngH) * (parseInt(pc[1]) / 100));
	}
	x = parseInt(x);
	y = parseInt(y);

	// Handle backgroundRepeat.
	var repeatX = { 'repeat': 1, 'repeat-x': 1 }[bgR],
		repeatY = { 'repeat': 1, 'repeat-y': 1 }[bgR];
	if (repeatX) {
		x %= pngW;
		if (x > 0) x -= pngW;
	}
	if (repeatY) {
		y %= pngH;
		if (y > 0) y -= pngH;
	}

	// Go!
	this.hook.enabled = 0;
	if (!({ relative: 1, absolute: 1 }[elm.currentStyle.position])) {
		elm.style.position = 'relative';
	}
	var count = 0,
		xPos,
		maxX = repeatX ? elmW : x + 0.1,
		yPos,
		maxY = repeatY ? elmH : y + 0.1,
		d,
		s,
		isNew;
	if (pngW && pngH) {
		for (xPos = x; xPos < maxX; xPos += pngW) {
			for (yPos = y; yPos < maxY; yPos += pngH) {
				isNew = 0;
				if (!tiles.cache[count]) {
					tiles.cache[count] = document.createElement('div');
					isNew = 1;
				}
				var clipR = (xPos + pngW > elmW ? elmW - xPos : pngW),
					clipB = (yPos + pngH > elmH ? elmH - yPos : pngH);
				d = tiles.cache[count];
				s = d.style;
				s.behavior = 'none';
				s.left = xPos + 'px';
				s.top = yPos + 'px';
				s.width = clipR + 'px';
				s.height = clipB + 'px';
				s.clip = 'rect(' +
					(yPos < 0 ? 0 - yPos : 0) + 'px,' +
					clipR + 'px,' +
					clipB + 'px,' +
					(xPos < 0 ? 0 - xPos : 0) + 'px)';
				s.display = 'block';
				if (isNew) {
					s.position = 'absolute';
					s.zIndex = -999;
					if (elm.firstChild) {
						elm.insertBefore(d, elm.firstChild);
					} else {
						elm.appendChild(d);
					}
				}
				this.fix(d, pngSrc, 0);
				count++;
			}
		}
	}
	while (count < tiles.cache.length) {
		this.fix(tiles.cache[count], '', 0);
		tiles.cache[count++].style.display = 'none';
	}

	this.hook.enabled = 1;

	// Cache so updates are infrequent.
	tiles.old = {
		w: elmW,
		h: elmH,
		x: bgX,
		y: bgY,
		r: bgR
	};
};


IEPNGFix.update = function() {
	// Update all PNG backgrounds.
	for (var i in IEPNGFix.data) {
		var t = IEPNGFix.data[i].tiles;
		if (t && t.elm && t.src) {
			IEPNGFix.tileBG(t.elm, t.src);
		}
	}
};
IEPNGFix.update.timer = 0;

if (window.attachEvent && !window.opera) {
	window.attachEvent('onresize', function() {
		clearTimeout(IEPNGFix.update.timer);
		IEPNGFix.update.timer = setTimeout(IEPNGFix.update, 100);
	});
}

/// <reference name="MicrosoftAjax.debug.js" />
/// <reference name="MicrosoftAjaxTimer.debug.js" />
/// <reference name="MicrosoftAjaxWebForms.debug.js" />
/// <reference name="AjaxControlToolkit.ExtenderBase.BaseScripts.js" assembly="AjaxControlToolkit" />
/// <reference name="AjaxControlToolkit.Common.Common.js" assembly="AjaxControlToolkit" />

//////////////////////////////////
//								//
//	YourNewsPage JavaScripts	//
//								//
//////////////////////////////////


/*

	*** CONTENTS ***
	* General methods
	* Item actions
	* Article actions
	* Comment actions
	* Fixes
*/



// --------------- //
// GENERAL METHODS //
// --------------- //

// Body onload
$(document).ready(
	function()
	{
		// Shadowbox options
		var options = {
			resizeLgImages:     true,
			handleUnsupported:  'remove',
			keysClose:          ['c', 27] // c or esc
		};

		// Initializa the image viewer
		Shadowbox.init(options);
		
		// Change rel="external" to target="_blank"
		externalLinks();
	}
);

function defineType(type)
{
	if(type == "article")
	{
		returnval = "a";
	}
	else if(type == "particle")
	{
		returnval = "p";
	}
	else
	{
		alert("We're sorry, an error occurred!\nOur technical staff has been informed"); // Error
		return;
	}
	return returnval;
}

function externalLinks()
{ 
	if (!document.getElementsByTagName) return;
	var anchors = document.getElementsByTagName("a");
	for (var i=0; i<anchors.length; i++) {
		var anchor = anchors[i];
		if (anchor.getAttribute("href") && anchor.getAttribute("rel") == "external")
			anchor.target = "_blank";
	}
}
if(typeof(Sys)!=='undefined')Sys.Application.notifyScriptLoaded();