﻿jQuery(function() {
    initialiseTagging();
    onLoad();
});

function onLoad() {
    setTimeout(defer_onLoad, 1000);
    if($("#formReportResults").length > 0)
        $("#formReportResults").tablesorter();
}
function defer_onLoad()
{
    // Tabs / full page toggle
    jQuery('#pTabsSingle').click(function() { jQuery('body').removeClass('has_tabs'); setTabSwitch(0); });
    jQuery('#pTabsTabbed').click(function() { jQuery('body').addClass('has_tabs'); setTabSwitch(1); });
    limitTabs();
    initialiseDocView();
    
    // initialiseDragAndDropAssociationEditors()
    // submit and redirect
    jQuery("a.submitAndRedirect").click(function() {
        return submitAndRedirect(this);
    });
    try	{
        resize_start(); //defined in dragdrop/resize.js
    }catch (e) {}
    
    jQuery("ul.landingBlockParent").each(function() {
            dragsort.makeListSortable(this,saveOrder);
    });
    jQuery("ul.landingblock").each(function() {
            dragsort.makeListSortable(this,saveOrder);
    });

    //now hide objects on menu pop
    jQuery('#nav li').css({minWidth : '5em' });
    if (jQuery.browser.msie && parseInt(jQuery.browser.version)<=6) {
       ie6MenuBodge();
       ie6TipBodge();
    };  
    var x = '' + window.location;
    if (x.indexOf('Globals.')>-1) {
        jQuery('#associationfilterDiv').show();
    }  
    try {
        showNavAway();
    } catch (e) { }

    $(".datestart").datepicker({
        dateFormat: "yy-mm-dd",
        changeMonth: true,
        changeYear: true,
        maxDate: new Date(),
        onSelect: function (dateText, inst) {
            var the_date = new Date(dateText);
            $(".dateend").datepicker('option', 'minDate', the_date);
        }
    });
    $(".dateend").datepicker({ dateFormat: "yy-mm-dd", changeMonth: true, changeYear: true, maxDate: new Date() });
    //hide the filter box if no form elements have a value
    $('#holdingcontainer form:first').each(function () {
        var can_close = true;
        $(':input:not(:submit)', this).each(function () {
            if (can_close && $(this).val() != '')
                can_close = false;
        });
        if (can_close)
            $(this).children('.introcontent').hide();
    });
}

function initialiseDragAndDropAssociationEditors(){
    // Initialise the table
    jQuery(".associationList").tableDnD({
	    onDragClass: "dragRow",
	    onDrop: function(table, row) {
            var rows = table.tBodies[0].rows;
            var rowAhead;
            var length = rows.length;
            for (var i=0; i<length; i++) {
                if(rows[i].id == row.id) {
                    if(i == (length - 1))
                        rowAhead = 0;
                    else
                        rowAhead = rows[i+1].id;
                }
            }
            if(rowOrigAhead == rowAhead) {
                // Do nothing as the row hasn't moved
            }else{
                disableActionButtons(); 
                jQuery(row).parents("table")[0].style.opacity=0.25     
	            ajaxPlaceItemBefore((rowAhead == 0) ? 0 : rowAhead.split(":")[1],row.id.split(":")[1],row.id.split(":")[0]);
	        }
	    },
		onDragStart: function(table, row) {
		    var sib = jQuery(row).next();
		    rowOrigAhead = (sib.length > 0) ? sib.attr('id'):0;
		}
	});
}

// JScript File
if ((typeof ToolMan) != 'undefined') {
	var dragsort = ToolMan.dragsort()
	var junkdrawer = ToolMan.junkdrawer()
	var autosaveTimer;
	function saveOrder(item) {
		return false;
		var group = item.toolManDragGroup
		var list = group.element.parentNode
		var id = list.getAttribute("id")
		if (id == null) return
		group.register('dragend', function() {
			ToolMan.cookies().set("list-" + id,
					junkdrawer.serializeList(list), 365)
		})
	}
}

function initialiseDocView(){
    jQuery('#pTabsSingle').click(function() { setCookie("DisplayTabs","0",180,"/","",false); jQuery('body').removeClass('has_tabs'); setTabSwitch(0); } );
    jQuery('#pTabsTabbed').click(function() { setCookie("DisplayTabs","1",180,"/","",false); jQuery('body').addClass('has_tabs'); setTabSwitch(1); } );
    if(jQuery('#pTabsTabbed').attr("checked") == true)
    {
        jQuery('body').addClass('has_tabs');
        setTabSwitch(1);
    }else{
        setTabSwitch(0);
        jQuery('body').removeClass('has_tabs');
    }
}

function initialiseTagging() {
	if ($('#tagName').length > 0) $('#tagName').autocomplete({
		source: '/tags.axd',
		minLength: 2,
		appendTo: '.tagEditor',
		select: function (event, ui) {
			$(this).val(ui.item.label);
			return false;
		},
		focus: function (event, ui) {
			$(this).val(ui.item.label);
			return false;
		}
	});
    $('#addtags').live('click', function() {
        jQuery("#ajaxContainer").addClass('waiting');
        var loc = window.location.href;
        if (loc.indexOf('#') > 0) loc = loc.substring(0, window.location.href.indexOf('#'));
        loc += '?partial=partial';
        var poststr = "&action=partial&subaction=add tags&fieldPath=Tags&tagName=";
        poststr += $('#tagName').val();
        if (!permissions_open) {
            jQuery("#ajaxDialogContents").html("<img src = '/cms/img/wait2.gif' style = 'left:50%;margin-left:-80px;top:45%;position:absolute;'/>");
            closeAjaxDialog = true;
        }
        jQuery('#fieldWrapper_tags').load(loc, jQuery.query(poststr), function(data, textStatus) {
            alertContents(data, textStatus);
        });
        return false;
    });
    $('#deletetags').live('click', function() {
        jQuery("#ajaxContainer").addClass('waiting');
        var loc = window.location.href;
        if (loc.indexOf('#') > 0) loc = loc.substring(0, window.location.href.indexOf('#'));
        loc += '?partial=partial';
        var poststr = "&action=partial&subaction=delete selected tags&fieldPath=Tags&deletetagassociations=";
        $('input[name=deletetagassociations]:checked').each(function(){ poststr += jQuery(this).val() + ","; });
        if (!permissions_open) {
            jQuery("#ajaxDialogContents").html("<img src = '/cms/img/wait2.gif' style = 'left:50%;margin-left:-80px;top:45%;position:absolute;'/>");
            closeAjaxDialog = true;
        }
        jQuery('#fieldWrapper_tags').load(loc, jQuery.query(poststr), function(data, textStatus) {
            alertContents(data, textStatus);
        });
        return false;
    });
}

function toggleRowForEdit(row,edit)
{
	jQuery(row).find('.showOnEdit').each(function()
	{
		
		this.style.visibility=(edit)?'':'hidden';
		this.style.height=(edit)?'':'1px';
		this.style.overflow=(edit)?'':'hidden';
	});
	
	jQuery(row).find('.hideOnEdit').each(function()
	{
		this.style.display=(edit)?'none':'block';
	});
	return false;
}
function limitTabs(){
	$("#tabsLess a").click(
		function() {
		jQuery('.page_menu').attr('id','tabsPrimary');
		if ($.browser.msie) { ieFixTabToggle(); }
		return false;
		}
	);
	$("#tabsMore a").click(
		function() {
		jQuery('.page_menu').attr('id','tabsAll');
		if ($.browser.msie) { ieFixTabToggle(); }
		return false;
		}
	);
}
function ieFixTabToggle(){
    if(jQuery('.page_menu').attr('id') == 'tabsPrimary') {
        jQuery('.tabSecondary').show();
        jQuery('.tabSecondary').hide();
    }
    else {
        jQuery('.tabSecondary').show();
    }
}
function setCookie(name, value, expires, path, domain, secure) {
    var today = new Date();
    today.setTime( today.getTime() );

    if ( expires ) expires = expires * 1000 * 60 * 60 * 24;

    var expires_date = new Date( today.getTime() + (expires) );

    document.cookie = name+'='+ value +
        ( ( expires ) ? ';expires='+expires_date.toGMTString() : '' ) +
        ( ( path ) ? ';path=' + path : '' ) +
        ( ( domain ) ? ';domain=' + domain : '' ) +
        ( ( secure ) ? ';secure' : '' );
}

function toggle(obj,parent,parentid,childid,depth,url)
    {
    if (parent.className == 'parent_closed') {
        parent.className = 'parent_open';
        setPersistentCookie ('sitemap_' + parentid, '1');
        if (jQuery(parent).find('.sitemapul.loadingDiv'))
        {
			var myurl=url.replace(/child\=[0-9]*\&?/i,"");
			myurl=myurl.replace(/depth\=[0-9]*\&?/i,"");
			if (url.indexOf('?') > 0) {myurl+= '&';} else {myurl += '?';}
			myurl=myurl.replace('&&','&');
			myurl+= 'child=' + childid + '&depth=' + depth;
			jQuery(parent).find('.sitemapul').load(myurl, function(data, textStatus) {alertContents(data, textStatus);});
			
        }
    } else if(parent.className == 'parent_open') {
        parent.className = 'parent_closed';
        setPersistentCookie ('sitemap_' + parentid, '0');
    }
    return false;
    }

var WindowObjectReferenceOfRequestedPopup , WindowObjectReferenceOfIntermediaryPopup;
	
function openPopup(strUrl, strTarget) {
    var windowWidth, windowHeight, windowLeft, windowTop;
    if (typeof window.screenX == "number" &&
        typeof window.innerWidth == "number") {
        windowWidth = window.innerWidth * 0.68;
        windowHeight = window.innerHeight * 0.68;
        windowLeft = window.screenX + window.innerWidth * 0.16;
        windowTop = window.screenY + window.innerHeight * 0.16;
    } else if (typeof window.screenTop == "number" &&
        typeof document.documentElement.offsetHeight == "number") {
        windowWidth = document.documentElement.offsetWidth * 0.68;
        windowHeight = document.documentElement.offsetHeight * 0.68;
        windowLeft = window.screenLeft + document.documentElement.offsetWidth * 0.16;
        windowTop = window.screenTop - 50;
    } else {
        windowWidth = 500;
        windowHeight = 250;
        windowLeft = 60;
        windowTop = 40;
    }
    if (WindowObjectReferenceOfRequestedPopup == null ||
        WindowObjectReferenceOfRequestedPopup.closed) {
        WindowObjectReferenceOfRequestedPopup = window.open(strUrl, strTarget, "top=" + windowTop + ",left=" + windowLeft + ",width=" + windowWidth + ",height=" + windowHeight + ",menubar,toolbar,location,resizable,scrollbars,status");
    } else {
        WindowObjectReferenceOfRequestedPopup.focus();
    }
}

function disableActionButtons() {
    jQuery('#top_buttons input, #buttons input').css({visibility : 'hidden'});
}

function enableActionButtons() {
    jQuery('#top_buttons input, #buttons input').css({visibility : 'visible'});
}

function formSubmit() {
    disableActionButtons();
    updateXHTMLValue();
}

// Handles a file-post back
function doFilePost(fieldId, filePath) {
  jQuery('#'+fieldId).val(filePath);
  jQuery('#img_'+ fieldId)
    .attr('src','/cms/image' + filePath + '/large.aspx')
	.show()
	.parent().attr('href',filePath);
}

function handleDate(path) {
    var eDay = document.getElementById (path + '-day').value;
    var eMonth = document.getElementById (path + '-month').value;
    var eYear = document.getElementById (path + '-year').value;
    document.getElementById (path).value = eDay + ' ' + eMonth + ' ' + eYear;
    checkField(document.getElementById (path));
}
            
function AutoSave() {
	if (document.getElementById("RedirectToURL")) {
             jQuery("#RedirectToURL").val('/cms/timeout.aspx');
             jQuery('#mainForm').submit();
     }
     else {
            window.location.href = "/cms/logout.aspx";
     }
     return false;   
}
    
function tabSwitch(cookiename, newposition) {
	updateXHTMLValue();
    jQuery('.page_menu .current').removeClass('current');
    jQuery('#tabposition'+newposition).addClass('current');
    jQuery(".tabpage.current").removeClass('current');
    jQuery("#container" + newposition).addClass('current');
    setPersistentCookie (cookiename, newposition);
    var bTag = document.getElementsByTagName("body")[0].className;
    if(bTag.indexOf('has_tabs')<0) {
        window.location='#container' + newposition;
    }
}

function switchMiniTab(tab) {
    jQuery('#minitabs .current').removeClass('current');
    jQuery(tab.parentNode).addClass('current');
    jQuery('#ajaxDialogContents .minitab').each (function() { this.style.display="none"; });
	jQuery('#' + tab.id + '_contents').css('display','block');//style.display='block';
}

function errorClick(errorid, cookiename) {
	var position = jQuery('#'+errorid).parents('.tabpage:first').attr('id').replace('container','');
    tabSwitch(cookiename, position);
}
    
function showUL(ele) {
	jQuery(ele).children('ul').show();
}

function hideUL(ele) {
	jQuery(ele).children('ul').hide();
}

var menuTimeouts = new Array();
function ie6MenuBodge() {
    var pNavi = document.getElementById('nav');
    var arrLi = pNavi.getElementsByTagName('li');
    for (var i=0;i<arrLi.length;i++)
    {
		arrLi[i].id = 'menuLi-'+i;
        arrLi[i].onmouseover = function() {
            clearTimeout(menuTimeouts[this.id]);
            showUL(this);
        }
        arrLi[i].onmouseout = function() {
            var tmpE = this;
            menuTimeouts[this.id] = setTimeout(function() {hideUL(tmpE)}, 50);
        }
    }
}
function ie6TipBodge() {
	jQuery('div.tip')
		.mouseover(function() {jQuery(this).children().show();})
		.mouseout(function() {jQuery(this).children().hide();});
}        

function submitAndRedirect(obj)
    {
     jQuery("#RedirectToURL").val(obj.href);
     jQuery("#mainForm").submit();
     return false;
}

// Hides object to resolve horrible [object] z-index problems
function hideObjects() {
	jQuery('object').css({visibility : 'hidden'});
    jQuery('body').css({overflow : 'hidden'});
}
function showObjects()
{
    if (jQuery('#ajaxContainer:visible').length >0 ) return false;
	jQuery('object').css({visibility : 'visible'});
    jQuery('body').css({overflow : ''});
}

function hideShowHelpbox(ele) {
	if(ele.className=='introexpand') {
		ele.className ='introclose';
		ele.parentNode.style.height ='auto';
	}
	else {
		ele.className ='introexpand';
		ele.parentNode.style.overflow ='hidden';
		ele.parentNode.style.height ='25px';
	}
	return false;
}

function hideShowInfobox(ele) {
	if(ele.className=='introexpand') {
		ele.className ='introclose';
		ele.parentNode.className ="infobox";
		setPersistentCookie("infobox_disp","show");
	}
	else {
		ele.className ='introexpand';
		ele.parentNode.className ="infocollapse";
		setPersistentCookie("infobox_disp","hide");
	}
	return false;
}
// Positions the action div in IE7
function posActionDiv()
{
    return document.documentElement.scrollTop + document.documentElement.offsetHeight - 202 + 'px' ;// + document.body.parentNode.offsetHeight + 'px';
}
function setPersistentCookie(name,val)
{
    var DaysToLive = 30; // CHANGE number 30 to number of days you want cookie to persist.
    var now = new Date();
    then = now.getTime() + (DaysToLive * 24 * 60 * 60 * 1000);
    now.setTime(then);
    document.cookie = name + '=' + val + '; expires=' + now.toGMTString() + '; path=/';
}

function updateXHTMLValue() {
	jQuery('object.fieldInputXHTML').each(function() {
		var e = jQuery('#'+ jQuery(this).attr('name'));
		var val = this.value ? this.value : e.val();
		jQuery(this).children().each(function() {
			if(this.name=='Value') this.value = val;
		});
		e = val;
	});
}

function hideShowSection(obj,path)
{
	updateXHTMLValue();
	//hides or shows a container
	if(document.getElementsByTagName('BODY')[0].className.indexOf('has_tabs') > -1) return false;
    if (obj.parentNode.className == "tabpage collapsed_yes")
    {
        obj.parentNode.className = "tabpage current";
        setPersistentCookie("hide_" + path , 0)
    }
    else
    {
        obj.parentNode.className = "tabpage collapsed_yes";
        setPersistentCookie("hide_" + path , 1)
    }        
    return false;
}

function filterType(obj) {
    newfilter = obj.value;

    address = '' + window.location;
    x = address.split('/');

    schema = x[x.length-2];
    z = schema.split('.');
    newschema = '';
    for(y=0;y<2;y++) {
    	if(newschema.length>0) newschema = newschema + '.'
    	newschema = newschema + z[y];
    }
    if(newfilter.length>0) newschema = newschema + '.' + newfilter;
    x[x.length-2] = newschema;
    window.location = x.join('/');
}

function clickPreview(url) {
		hideObjects(); //defined in general .js
        //hide the full screen link as we may not need it
        jQuery("#ajaxDialogExpandLink").hide();
        jQuery('#ajaxCloseBox').attr('onclick','');
        jQuery('#ajaxCloseBox').attr('href','javascript:void(ajaxCloseDialog());');
        jQuery('#ajaxContainer').show();
        jQuery('#ajaxTitle').html("Image preview");
        jQuery('#ajaxDialogContents').html("<img src = '" + url + "'/>");
}
