/* $Id: functions.js,v 1.240 2008/06/09 10:58:01 sadu Exp $
 * Javascript functions used throughout TABS
 * (c) Digital Advertising and Marketing Ltd 2000-2007
 */

if(typeof(tz_set_domain)!='undefined') {
    document.domain='uk.tz';
 }

function debug(str) {
    loadXMLDoc('debug.phtml', 'debug_string=' + escape(str));
}

//window.onerror=handleErr;

function handleErr(msg,url,l) {
	txt="Error: " + msg + " URL: " + url + " Line: " + l;
	debug(txt);
	return true;
}


function log_error() {
    values = "";
    loadXMLDoc('error.phtml', values);
}

function show_error(type) {
    switch(type) {
    case 'no_input':
		wice_console('info', no_input_header, '', '', '', no_input_text, 'OK');
		break;

    case 'no_results':
		wice_console('info', no_results_header, '', '', '', no_results_text, 'OK');
		break;

    default:
		wice_console('error', generic_error_header, '', '', '', generic_error_text, 'OK');
    }
}

// TZ Suite Nav functions
function load_tz_suite(imgID){
    var loc = document.getElementById(imgID);
    var locT = getRealTop(loc);
    var locL = getRealLeft(loc);
    var flash_nav = '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0" width="150" height="150" id="tz_suite_nav" align="middle"><param name="allowScriptAccess" value="sameDomain" /><param name="movie" value="images/tz_suite_nav.swf?zebraone_url='+zebraone_url+'&response_url='+response_url+'&tabs_url='+tabs_url+'&search_url='+search_url+'" /><param name="quality" value="high" /><embed src="images/tz_suite_nav.swf?zebraone_url='+zebraone_url+'&response_url='+response_url+'&tabs_url='+tabs_url+'&search_url='+search_url+'" quality="high" width="150" height="150" name="tz_suite_nav" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" /></object>';
    //alert(locT+' '+locL);
    var tz_suite_div = document.createElement('DIV');
    tz_suite_div.setAttribute("id","tz-suite-div");
    //tz_suite_div.setAttribute("onmouseout","unload_tz_suite()");
    tz_suite_div.setAttribute("style","position:absolute;width:150px;height:150px;top:"+locT+"px;left:"+(locL-126)+"px;");
    var thebody = document.getElementById('doc-body');
    thebody.insertBefore(tz_suite_div, thebody.firstChild);
    //thebody.appendChild(tz_suite_div);
    // set style properties after the element is created as browsers are shit in applying this stuff properly
    var suite_div = document.getElementById('tz-suite-div');
    suite_div.style.position = 'absolute';
    // suite_div.style.display = 'block';
    // suite_div.style.background = 'white';
    suite_div.style.top = locT+'px';
    suite_div.style.left = locL-126+'px';
    /* if(domtype=='msie'){
	suite_div.style.left = locL+'px';
    } else {
	suite_div.style.left = locL+'px';
    }*/
    suite_div.style.width = 150+'px';
    suite_div.style.height = 150+'px';
    suite_div.style.clear = 'both';
    suite_div.style.zIndex = '99999';
    suite_div.innerHTML = flash_nav;

}

function unload_tz_suite() {
    var tz_suite_div = document.getElementById('tz-suite-div');
    if(tz_suite_div != 'undefined' && tz_suite_div){
		document.getElementById('doc-body').removeChild(tz_suite_div);
    }
}

// TZ SEARCH Links
function load_tz_search_links(){
    var tz_suite_div = document.getElementById('tz-suite-div');
    var locT = getRealTop(tz_suite_div);
    var locL = getRealLeft(tz_suite_div);
    var tz_search_links = document.createElement('DIV');
    tz_search_links.setAttribute('id','tz-search-links');
    thebody = document.getElementById('doc-body');
    thebody.insertBefore(tz_search_links, thebody.firstChild);
    // document.getElementById('doc-body').appendChild(tz_search_links);
    // set properties after the element is created as browsers are shit in applying this stuff properly
    var search_links = document.getElementById('tz-search-links');
    search_links.style.position = 'absolute';
    search_links.style.background = '#ea8f1c';
    search_links.style.top = locT+'px';
    search_links.style.left = locL-200+'px';
    search_links.style.width = 200+'px';
    search_links.style.height = 150+'px';
    search_links.style.fontSize = '9pt';
    search_links.style.zIndex = '99999';
    search_links.style.overflow = 'auto';
    search_links.style.textAlign = 'left';
    search_links.innerHTML = "<div style='padding:2px;font-size:9pt;background-color:#990000;color:white;font-weight:900;'>" + dyn_text['search-links-select-from-list'] + "</div>";
    if (search_links_name.length > 0) {
		var ol_list = document.createElement('OL');
		ol_list.setAttribute('id','links-list');
		document.getElementById('tz-search-links').appendChild(ol_list);
		for(i=1;i<search_links_name.length;i++) {
			var ol_li = document.createElement('LI');
			ol_li.setAttribute('id','li-link-'+i);
			document.getElementById('links-list').appendChild(ol_li);
			var new_link = document.createElement('A');
			new_link.setAttribute('id','tz_search_link_'+i);
			new_link.setAttribute('href','javascript:document.forms.product_'+i+'.submit();void(0);');
			new_link.setAttribute('title',search_links_name[i]);
			document.getElementById('li-link-'+i).appendChild(new_link);
			var new_link_a = document.getElementById('tz_search_link_'+i);
			new_link_a.innerHTML = search_links_name[i];
			//new_link_a.style.display = 'block';
			//new_link_a.style.padding = 2+'px';
			document.getElementById('links-list').style.fontSize = 80+'%';
		}
    } else {
		search_links.innerHTML = '<div style="padding:10px;font-size:90%;color:white;"><strong>' + dyn_text['no-search-links-available'] + '</strong></div>';
    }
}

function unload_tz_search_links(){
    var tz_search_links = document.getElementById('tz-search-links');
    if(tz_search_links != 'undefined' && tz_search_links){
		document.getElementById('doc-body').removeChild(tz_search_links);
    }
}

/* confirm console action */
function wice_console(console, console_header, action, item, item_id, str, action_text) {
    var error_div = document.getElementById('error-console');
    var error_msg = document.getElementById('error-console-body');
    var error_icon = document.getElementById('error-icon-image');
    var error_close_icon = document.getElementById('error-close-icon');
    var error_header_text = document.getElementById('error-error-text');
    var error_header = document.getElementById('error-error');
    if(domtype == 'safari' || domtype == 'mozilla') {
	var winW = window.innerWidth;
	elmW = getRealWidth(error_div);
	error_div.style.left = ((winW - 400) / 2) + 'px';
    }
    if(domtype == 'msie') {
	var winW = document.body.offsetWidth;
	elmW = getRealWidth(error_div);
	error_div.style.left = ((winW - 400) / 2) + 'px';
    }
    if (error_div.style.display == 'none') {
	//if (item_id) {

	// show console and change header text and icon
	error_div.style.display = 'block';
	error_header_text.innerHTML = console_header;
	error_icon.src = 'images/icon_'+console+'_console.gif';

	// replace string values
	item_action = str.replace(/{action}/g, action);
	item_action = item_action.replace(/{action_text}/g, action_text);
	item_action = item_action.replace(/{item}/g, item);
	item_action = item_action.replace(/{id}/g, item_id);
	error_msg.innerHTML = item_action;

	// apply style - className was not working - maybe we can tweak later
	if (console == 'confirm') {
	    error_header.style.backgroundColor = '#ef922e';
	    error_close_icon.style.backgroundColor = '#ef922e';
	    error_msg.style.borderColor = '#ef922e';
	} else if (console == 'info') {
	    error_header.style.backgroundColor = '#336699';
	    error_close_icon.style.backgroundColor = '#336699';
	    error_msg.style.borderColor = '#336699';
	} else if (console == 'error') {
            error_header.style.backgroundColor = '#990000';
            error_close_icon.style.backgroundColor = '#990000';
            error_msg.style.borderColor = '#990000';
        }
	if(domtype == 'msie') {
	    hide_conflicting_elements(error_div);
	}
	//}
    } else {
	show_all_conflicts();
	error_div.style.display = 'none';
    }
}


var extra_action = null;
/* error or debug window */
function tabs_error(str) {
    var error_div = document.getElementById('error-console');
    var error_msg = document.getElementById('error-console-body');
    var error_icon = document.getElementById('error-icon-image');
    var error_close_icon = document.getElementById('error-close-icon');
    var error_header_text = document.getElementById('error-error-text');
    var error_header = document.getElementById('error-error');
    if(domtype == 'safari' || domtype == 'mozilla') {
		var winW = window.innerWidth;
		error_div.style.left = ((winW - 400) / 2) + 'px';
    }
    if(domtype == 'msie') {
		var winW = document.body.offsetWidth;
		error_div.style.left = ((winW - 400) / 2) + 'px';
    }
    if (error_div.style.display == 'none') {
		if (str) {
			hide_conflicting_elements(error_div);
			error_div.style.display = 'block';
			error_msg.innerHTML = str;
			error_header_text.innerHTML = 'Error';
			error_header.style.backgroundColor = '#990000';
			error_icon.src = 'images/icon_error_corner.gif';
			error_close_icon.style.backgroundColor = '#990000';
			error_msg.style.borderColor = '#990000';
		}
    } else {
		show_all_conflicts();
		error_div.style.display = 'none';
		unload_indicator();

		// reset style if previously changed by other console
		error_header.style.backgroundColor = '#990000';
		error_icon.src = 'images/icon_error_corner.gif';
		error_close_icon.style.backgroundColor = '#990000';
		error_msg.style.borderColor = '#990000';
		if (extra_action != null) {
			extra_action();
			extra_action = null;
		}

		//the closing cross of the wice window will sometimes have had its default action added to, this resets the closing action
		if($("#error-close-link").attr("href") != 'javascript:tabs_error();void(0);'){
			$("#error-close-link").attr("href","javascript:tabs_error();void(0);");
		}

    }
}

function validate_format() {
    if (document.getElementById('format').value == '0') {
		document.getElementById('format-missing').style.display = 'block';
		document.getElementById('format-label').style.color = 'red';
    } else {
		document.getElementById('format-missing').style.display = 'none';
		document.getElementById('format-label').style.color = '#4F5553';
    }
}

function validate_cv_name() {
    if (document.getElementById('cv_name').value == '') {
		document.getElementById('cv_name-missing').style.display = 'block';
		document.getElementById('cv_name-label').style.color = 'red';
    } else {
		document.getElementById('cv_name-missing').style.display = 'none';
		document.getElementById('cv_name-label').style.color = '#4F5553';
    }
}

function validate_format_dimensions() {
    if (document.getElementById('format_dimensions').value == '0') {
		document.getElementById('format_dimensions-missing').style.display = 'block';
		document.getElementById('dimensions_name').style.color = 'red';
    } else {
		document.getElementById('format_dimensions-missing').style.display = 'none';
		document.getElementById('dimensions_name').style.color = '#4F5553';
    }
}

function validate_width() {
    if (document.getElementById('format_dimensions').value.substring(0, 2) == 'ud' && (document.getElementById('manual-width').value == '' || isNaN(document.getElementById('manual-width').value))) {
		document.getElementById('manual-width-missing').style.display = 'block';
		document.getElementById('manual-width-label').style.color = 'red';
    } else {
		document.getElementById('manual-width-missing').style.display = 'none';
		document.getElementById('manual-width-label').style.color = '#4F5553';
    }
}

function validate_height() {
    if (document.getElementById('format_dimensions').value.substring(0, 2) == 'ud' && (document.getElementById('manual-height').value == '' || isNaN(document.getElementById('manual-height').value))) {
		document.getElementById('manual-height-missing').style.display = 'block';
		document.getElementById('manual-height-label').style.color = 'red';
    } else {
		document.getElementById('manual-height-missing').style.display = 'none';
		document.getElementById('manual-height-label').style.color = '#4F5553';
    }
}

function missing_fields_highlight() {
    validate_format();
    validate_format_dimensions();
    validate_cv_name();
    validate_width();
    validate_height();
    if (document.getElementById('client_id').value == '') {
		document.getElementById('client_id-missing').style.display = 'block';
		document.getElementById('client_id-label').style.color = 'red';
    } else {
		document.getElementById('client_id-missing').style.display = 'none';
		document.getElementById('client_id-label').style.color = '#4F5553';
    }
    if (document.getElementById('project_id').value == '') {
		document.getElementById('project_id-missing').style.display = 'block';
		document.getElementById('project_id-label').style.color = 'red';
    } else {
		document.getElementById('project_id-missing').style.display = 'none';
		document.getElementById('project_id-label').style.color = '#4F5553';
    }
}

/* report functions */

var allow_reload = 1;
function abort_reload() {
    allow_reload = 0;
}

/* Reporting: pass date data from drop down menus
 *(day, month, year) to a single variable
 *(start date or end date)
 */

function passDateValue(for_me, from_me){
    if (from_me) {
		send_from = from_me;
    } else {
		send_from = for_me;
    }
    var d = document.getElementById(send_from+'_date');
    var m = document.getElementById(send_from+'_month');
    var y = document.getElementById(send_from+'_year');
    var dmy = document.getElementById(for_me);
    var dmy_value = y.value+'-'+m.value+'-'+d.value;
    dmy.value = dmy_value;
}


function form_submit(frm) {
    document.getElementById(frm).submit();
}

// Find out which DOM type we should be using, and put it in domtype

var domtype = '';

if (navigator.appVersion.indexOf("MSIE")!=-1 && navigator.userAgent.indexOf("Windows") != -1) {
    temp=navigator.appVersion.split("MSIE");
    version=parseFloat(temp[1]);
    ie_variant = 5;
    if (version>=5.5){
		domtype = 'msie';
    }
    if (version>=6.0) {
		ie_variant = 6;
    }
    if (version>=7.0) {
		ie_variant = 7;
    }
 } else {
    if (navigator.userAgent.indexOf("Mozilla/5.0")!=-1) {
		if (navigator.userAgent.indexOf("Safari")!=-1) {
			// You lie!
			domtype = 'safari';
		} else {
			//	alert(navigator.productSub);
			if (navigator.product=='Gecko') {
				domtype = 'mozilla';
			}
		}
    }
 }


// center IE6 and shadow fix for small resolutions

var server_errors_checked = false;

function fix_shadow() {

    if(domtype == 'msie') {
	if(ie_variant == 6) {
	    var ts_left = getRealTabsLeft();
	    var shell = document.getElementById('tabs-shell');
	    shell.style.left = ts_left;
	    // $("#tabs-shell").left('100');
	}
	if (document.body.offsetWidth < 900) {
	    $("#tabs-shadow").hide();
	} else {
	    $("#tabs-shadow").show();
	}
    } else {
	if (window.innerWidth < 900) {
	    $("#tabs-shadow").hide();
	} else {
	    $("#tabs-shadow").show();
	}
    }


}

$(document).ready(function(){
    if($("#tabs-shell").is("div")){

	$("#tabs-loading").hide();
	$("#tabs-shell").show();

	fix_shadow();

	if (!server_errors_checked) {
	    check_server_errors();
	    server_errors_checked = true;
	}

	// position dfa upload layer
	if ($("#dfa-upload-layer").is("div")) {
	    position_dfa_upload_layer();
	}

	// set nav tooltips
	$('#setup-edit-options li').ToolTip(
           {
               className: 'dc-buttons-tooltip',
	       position: 'top',
               delay: 200
           }
         );
	 $('#test-setup-options li').ToolTip(
           {
               className: 'dc-buttons-tooltip',
	       position: 'top',
               delay: 200
           }
          );
	  $('#dc-utilities img').ToolTip(
            {
               className: 'dc-buttons-tooltip',
	       position: 'top',
               delay: 200
            }
          );
	  $('#dc-footer-help-link img').ToolTip(
            {
               className: 'dc-buttons-tooltip',
	       position: 'top',
	       delay: 200
            }
           );

	   $('#configure-utils').Draggable(
             {
                handle: '#configure-utils-header',
                zIndex: 2000
             }
           );
        }
    }
);

// center login only for ie

function center_login() {
    if(domtype == 'msie' && ie_variant == 6) {
		var elm = document.getElementById('tabs-shell');
		var winW = document.body.offsetWidth;
		elmW = getRealWidth(elm);
		elm.style.left = ((winW - elmW) / 2) - 10 + 'px';
    }
    document.forms['login'].ADMAN_AUTH_USER.focus();
}

// load and show iframes

function load_iframe(i_frame, url) {
    var reselm = document.getElementById(i_frame);
    var currentsrc = reselm.src;
    if (currentsrc != tabs_http_base + url) {
		reselm.src = url;
		if(domtype == 'safari') {
			reselm.style.display='block';
		}
    }
}

function show_page(loader, i_frame) {
    var hideelm = parent.document.getElementById(loader);
    var showelm = parent.document.getElementById(i_frame);
    hideelm.style.display = 'none';
    showelm.style.display = 'block';
}

// loading indicator functions

function load_indicator(div) {
    if (document.getElementById('loading-indicator') == null) {
		var newImg = document.createElement('img');
		newImg.src = 'images/loader.gif';
		newImg.alt = 'Processing';
		newImg.border = '0';
		newImg.align = 'left';
		newImg.id = 'loading-indicator';
		//newImg.style = 'margin-right:3px;';
		parentElm = document.getElementById(div);
		parentElm.insertBefore(newImg, parentElm.firstChild);
    } else {
		unload_indicator();
		load_indicator(div);
    }
}

function unload_indicator() {
    var elem = document.getElementById('loading-indicator');
    if(typeof(elem) != 'undefined' && elem) {
		elem.parentNode.removeChild(elem);
    }
}

// globals

function AJAXObj() {

    // ReadyState definitions
    this.ReadyState = new Object();
    this.ReadyState.Uninitialized = 0;
    this.ReadyState.Loading = 1;
    this.ReadyState.Loaded = 2;
    this.ReadyState.Interactive = 3;
    this.ReadyState.Complete = 4;

    // ServerResponse definitions
    this.ServerResponse = new Object();
    this.ServerResponse.OK = 200;
    this.ServerResponse.Created = 201;
    this.ServerResponse.Accepted = 202;
    this.ServerResponse.NoContent =  204;
    this.ServerResponse.BadRequest = 400;
    this.ServerResponse.Forbidden = 403;
    this.ServerResponse.NotFound = 404;
    this.ServerResponse.Gone = 410;
    this.ServerResponse.ServerError = 500;

    this.Method = new Object();
    this.Method.Get = "GET";
    this.Method.Post = "POST";
    this.Method.Put = "PUT";
    this.Method.Delete = "DELETE";

    this._reqObj = null;
    this.enabled = null;
    this.callback = null;

    this._init();
}

AJAXObj.prototype._init = function() {
    this._reqObj = this._getXmlHttp()
    this.enabled = (this._reqObj != null)
}

	AJAXObj.prototype._getXmlHttp = function() {
		if (window.XMLHttpRequest) {
			return new XMLHttpRequest();
		} else if (window.ActiveXObject) {
			return new ActiveXObject("Microsoft.XMLHTTP");
		} else {
			return null;
		}
	}

		AJAXObj.prototype.set_callback = function(callback){
			this.callback = callback;
		}

			AJAXObj.prototype.send = function(url,vars) {
				var method = this.Method.Post; // maybe do something smart with this later on

				var a = this;

				this._reqObj.onreadystatechange =  function() {
					if (a._reqObj.readyState != a.ReadyState.Complete) return;
					if (a.callback) a.callback(a._reqObj.responseText);
				}

				vars = (vars)? vars : null ;
				this._reqObj.open(method, url, true);
				this._reqObj.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
				this._reqObj.send(vars);
			}

				var ajaxRequestStack = new Array();


var callback = null;
var req;

/* Same as in ZebraOne scriptFunctions.js - should maybe be a sharedFunctions.js somewhere ?*/
function new_XMLHttpRequest() {
	if (window.XMLHttpRequest) {
		return new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		return new ActiveXObject("Microsoft.XMLHTTP");
	} else {
		return null;
	}
}

function loadXMLDoc(url, vars, callback) {
    ind = ajaxRequestStack.length;
    ajaxRequestStack[ind] = new AJAXObj;
    if (callback) ajaxRequestStack[ind].set_callback(callback);
    ajaxRequestStack[ind].send(url,vars);
}


function processReqChange() {
	//only if req shows "loaded"
    if (req.readyState == 4) {
		if (typeof(document.getElementById('loading-indicator')) != 'undefined' && document.getElementById('loading-indicator')) {
			unload_indicator();
		}
		if (req.responseText.substring(0, 2) == "-1") {
			show_error();
			var error_array = req.responseText.split('{splitter}');
			// kick off email to TZ tech because this shouldn't happen
			log_error(error_array[1]);
		} else {
			if (callback) {
				callback(req.responseText);
			}

			//if (req.status != 200) {
			//    tabs_error("There was a problem retrieving the XML data:\n" + req.statusText);
			//}

		}
    }
}

function re_colour_list() {
    listelm = document.getElementsByTagName('a');
    selected_list_live = new Array();
    selected_list_arch = new Array();
    for(var i=0; i<listelm.length; i++){
		if(listelm[i].id.substr(0,5) == "live-" && listelm[i].parentNode.style.display != "none") {
			selected_list_live.push(listelm[i]);
		}
		if(listelm[i].id.substr(0,5) == "arch-" && listelm[i].parentNode.style.display != "none") {
			selected_list_arch.push(listelm[i]);
		}
    }
    for(var i=0; i<selected_list_live.length; i++){
		if(i % 2 == 1){
			selected_list_live[i].parentNode.className = 'list-header';
		} else {
			selected_list_live[i].parentNode.className = 'list-header-second';
		}
    }
    for(var i=0; i<selected_list_arch.length; i++){
		if(i % 2 == 1){
			selected_list_arch[i].parentNode.className = 'list-header';
		} else {
			selected_list_arch[i].parentNode.className = 'list-header-second';
		}
    }
}

function delete_resource(resource_id) {
    values = 'action=delete&resource_id=' + resource_id;
    loadXMLDoc('./resource/mod_resource.phtml', values, resource_deleted_callback);
}

function edit_creative(creativeId) {
    var editButtonObj = document.getElementById('edit_button_' + creativeId);
    var creativeNameObj = document.getElementById('cv_name_' + creativeId);
    var newCreativeNameObj = document.getElementById('cv_name');
    if (editButtonObj.value == dyn_text['edit']) {
        creativeNameObj.disabled = false;
        newCreativeNameObj.disabled = true;
        editButtonObj.value = dyn_text['save'];
    } else {
		mod_creative(creativeId);
    }
}

// XmlHttpRequestObject CALLBACK FUNCTIONS //
function mod_user_details() {
    firstnameInput = document.getElementById('my-details-firstname');
    surnameInput = document.getElementById('my-details-surname');
    emailInput = document.getElementById('my-details-email');
    phoneInput = document.getElementById('my-details-phone');
    extensionInput = document.getElementById('my-details-ext');
    mobileInput = document.getElementById('my-details-mobile');
    //faxInput = document.getElementById('my-details-fax');
    address1Input = document.getElementById('my-details-address1');
    address2Input = document.getElementById('my-details-address2');
    //address3Input = document.getElementById('my-details-address3');
    townInput = document.getElementById('my-details-town');
    postcodeInput = document.getElementById('my-details-postcode');
    countryInput = document.getElementById('my-details-country');
    companyInput = document.getElementById('my-details-company');
    //tabsVirginInput = document.getElementById('my-details-tabs-virgin');

    values = 'firstname=' + firstnameInput.value;
    values += '&surname=' + surnameInput.value;
    values += '&email=' + emailInput.value;
    values += '&phone=' + phoneInput.value;
    values += '&extension=' + extensionInput.value;
    values += '&mobile=' + mobileInput.value;
    //values += '&fax=' + faxInput.value;
    values += '&fax=""'
		values += '&address1=' + address1Input.value;
    values += '&address2=' + address2Input.value;
    //values += '&address3=' + address3Input.value;
    values += '&address3=""';
    values += '&town=' + townInput.value;
    values += '&postcode=' + postcodeInput.value;
    values += '&country=' + countryInput.value;
    values += '&company=' + companyInput.value;
    /*
	  if (tabsVirginInput.checked) {
	  values += '&tabs_virgin=1';
	  } else {
	  values += '&tabs_virgin=0';
	  }
    */
    values += '&tabs_virgin=0';
    loadXMLDoc('./mod_user_details.phtml', values, mod_user_details_callback);
}

function mod_user_details_callback(responseText) {
    //document.location.reload();
    document.location.href='index.phtml?tab=5';
}

function mod_user_password() {
    new1Password = document.getElementById('password-details-new1');
    new2Password = document.getElementById('password-details-new2');

    if (trim(new1Password.value)=="" || trim(new2Password.value)=="") {
		return;
	}

    if (new1Password.value == new2Password.value) {
		values = "new_password=" + new1Password.value;
		loadXMLDoc('./mod_user_password.phtml', values, mod_user_password_callback);
    } else {
		//var error_text = '<div><div>The passwords you entered did not match</div><div style="height:30px;margin-top:10px;"><div style="height:30px;margin-top:10px;"><a id="confirm-ok-link" title="OK" href="javascript:tabs_error();void(0);" style="float:right;"><img style="float:left;margin-right:5px;" alt="OK" border="0" src="images/icon_ok.gif" /><div style="font-weight:900;margin-top:5px;margin-right:10px;">OK</div></a></div><div class="clear-dc"></div></div>';
		//var error_header = 'Error';
		//wice_console('error', error_header, '', '', '', error_text, '');
		tabs_error(dyn_text['password-mismatch']);

    }
}

function mod_user_password_callback(responseText) {
    extra_action = reload_password;
    var info_text = '<div><div>' + dyn_text['password-been-updated'] + '</div><div style="height:30px;margin-top:10px;"><div style="height:30px;margin-top:10px;"><a id="confirm-ok-link" title="OK" href="javascript:tabs_error();void(0);" style="float:right;"><img style="float:left;margin-right:5px;" alt="OK" border="0" src="images/icon_ok.gif" /><div style="font-weight:900;margin-top:5px;margin-right:10px;">OK</div></a></div><div class="clear-dc"></div></div>';
    var info_header = 'Info';
    wice_console('info', info_header, '', '', '', info_text, '');
    //reload_password();
    //alert('Password updated');
}

function reload_password() {
    document.location.reload();
    document.getElementById('password-details-new1').value = "";
    document.getElementById('password-details-new2').value = "";
}

function start_process() {
    elm = document.getElementById('tabs-tz-logo-image');
    elm.src = 'images/tabs_tz_logo_process.gif';
}

function stop_process() {
    elm = document.getElementById('tabs-tz-logo-image');
    elm.src = 'images/tabs_tz_logo.gif';
}



function replace(string,textIN,by) {
    strLength = string.length;
    txtLength = textIN.length;
    if ((strLength == 0) || (txtLength == 0)) return string;

    var i = string.indexOf(textIN);
    if ((!i) && (textIN != string.substring(0,txtLength))) return string;
    if (i == -1) return string;

    var newstr = string.substring(0,i) + by;

    if (i+txtLength < strLength){
		newstr += replace(string.substring(i+txtLength,strLength),textIN,by);
    }
    return newstr;
}

function toggle_project_field(id){
    // this function will probabaly go...
    var textDiv=document.getElementById("project_name_"+id);
    var formDiv=document.getElementById("project_textfield_div_"+id);
    textDiv.style.display='none';
    formDiv.style.display='block';
}


// functions to handle upload progress bar

var file_upload_time=0;
var total_size=0;
var upload_complete = false;

function upload_time_set() {
    if (file_upload_time!=0) {
		return true;
    }else{
		return false;
    }
}

function get_upload_time() {
	for(var i=0;i<file_inputs_count;i++) {
		local_filepath = (eval('document.getElementById("r_file_' + i + '").value'));
		var splitters = new Array("/","\\");
		for(var j=0;j<splitters.length;j++) {
			if (local_filepath.indexOf(splitters[j])!=-1) {
				path_bits = local_filepath.split(splitters[j]);
				if (!filename_is_clean(path_bits[path_bits.length-1].toString())) {
					wice_console('error', dyn_text['error'], '', '', '', dyn_text['bad-uploaded-filename'], 'OK');
					return;
				}

			}
		}
	}
    loadXMLDoc('upload_scripts/get_time.phtml', '', set_upload_time);
}

var bulk_project_id = 0;
var session_id;
function get_bulk_upload_time(project_id, s_id) {
	// validate fields first
	var formatEle = document.getElementById("format-"+project_id);
	if (formatEle.value=="0") {
		highlight_bulk_form_eles("format-label-"+project_id,"format-missing-"+project_id);
		return;
	} else {
		unhighlight_bulk_form_eles("format-label-"+project_id,"format-missing-"+project_id);
	}

	if (formatEle.value!="4") { // not overlay
		if (formatEle.value=="7") { // new window
			if (document.getElementById('format_options-'+project_id).value=="") {
				highlight_bulk_form_eles("format-options-label-"+project_id,"format-options-missing-"+project_id);
			} else {
				unhighlight_bulk_form_eles("format-options-label-"+project_id,"format-options-missing-"+project_id);
			}
		}

		unhighlight_bulk_form_eles("dimensions_name-"+project_id,"format_dimensions-missing-"+project_id);
		dimsEle = document.getElementById('format_dimensions-'+project_id);

		if (dimsEle.value.indexOf("ud-") != -1 || dimsEle.value != "0") {
			if (dimsEle.value.indexOf("ud-") != -1) {
				var dims_parts = dimsEle.value.split("ud-");
				var dims_id = (typeof(dims_parts)!='undefined')? dims_parts[1] : dimsEle.value ;

				enteredWidth = document.getElementById('manual-width-'+project_id).value;
				enteredHeight = document.getElementById('manual-height-'+project_id).value;

				if (enteredWidth && enteredHeight) {
					// set hidden vars
					document.getElementById('creative-width-'+project_id).value = enteredWidth;
					document.getElementById('creative-height-'+project_id).value = enteredHeight;
					unhighlight_bulk_form_eles("manual-width-label-"+project_id,"manual-width-missing-"+project_id);
					unhighlight_bulk_form_eles("manual-height-label-"+project_id,"manual-height-missing-"+project_id);
				} else {
					highlight_bulk_form_eles("manual-width-label-"+project_id,"manual-width-missing-"+project_id);
					highlight_bulk_form_eles("manual-height-label-"+project_id,"manual-height-missing-"+project_id);
					return;
				}
			} else {
				document.getElementById('creative-width-'+project_id).value = document.getElementById('manual-width-'+project_id).value;
				document.getElementById('creative-height-'+project_id).value = document.getElementById('manual-height-'+project_id).value;
			}
		} else {
			highlight_bulk_form_eles("dimensions_name-"+project_id,"format_dimensions-missing-"+project_id);
			return;
		}
	}

	bulk_project_id = project_id;
	session_id = s_id;
	loadXMLDoc('upload_scripts/get_time.phtml', '', set_bulk_upload_time);
}

function highlight_bulk_form_eles(labelEle, iconEle) {
	document.getElementById(iconEle).style.display = 'block';
	document.getElementById(labelEle).style.color = 'red';
}

function unhighlight_bulk_form_eles(labelEle, iconEle) {
	document.getElementById(iconEle).style.display = 'none';
	document.getElementById(labelEle).style.color = '#4f5553';
}
var progress_timer;
function set_upload_time(strData) {
    document.getElementById('add-new-file').submit();
    file_upload_time=strData;
    //callback=get_upload_state;
    // give it two seconds, files uploading quicker than this are too small
    progress_timer = setTimeout('get_upload_progress()',3000);
}

function set_bulk_upload_time(strData) {
    document.getElementById('project-format-selector-' + bulk_project_id).submit();
    file_upload_time=strData;
    //callback=get_upload_state;
    // give it two seconds, files uploading quicker than this are too small
    progress_timer = setTimeout('get_upload_progress()',4000);
}

var file_uploaded = false;
function get_upload_state(strData) {
    data_parts=strData.split('&');
    for (i=0;i<data_parts.length;i++) {
		eval(data_parts[i]);
    }

    if (parseInt(percent_uploaded)>98) {
		file_uploaded = true;
    }

    if (file_uploaded) {
		document.getElementById('upload-progress-bar').style.width = '100%';
		var output = dyn_text['upload-progress-text-complete'];
		file_uploaded = false;
    } else {
		document.getElementById('upload-progress-bar').style.width = percent_uploaded+'%';
		var output = dyn_text['upload-progress-text-1'] + ': ' + time_remaining + ' '+ dyn_text['upload-progress-text-2'] ;
		progress_timer = setTimeout('get_upload_progress()',2000);
    }
    document.getElementById('upload-status').innerHTML = output;
}


function get_upload_progress() {
    document.getElementById('upload-details-container').style.display='block';
    values='sessionid='+session_id+'&total_size='+total_size+'&start_time='+file_upload_time;
    loadXMLDoc('upload_scripts/upload_progress.phtml', values, get_upload_state); //get_upload_state
	clearTimeout(progress_timer);
}

// end progress bar functions

function filter_projects() {
    clientId = document.getElementById('client_id').value;
    projectSelectObj = document.getElementById('project_id');

    while(projectSelectObj.length>0){
        projectSelectObj.options[projectSelectObj.length-1]=null;
    }

    projectListObj = document.getElementById('project_id');

    if (clientId != "") {
	if (client_projects[clientId].length == 0) {
	    // FIXME: not sure about this... leave empty for now
	    //projectSelectObj.options[projectSelectObj.length] = new Option('Create a new project', 0);
	} else {
	    for (var i=0; i<client_projects[clientId].length; i++) {
		id = client_projects[clientId][i];
		name = projects[client_projects[clientId][i]];

		projectSelectObj.options[projectSelectObj.length] = new Option(name, id);
		if (selected_project_id != null && selected_project_id == id) {
		    projectSelectObj.options[projectSelectObj.length - 1].selected = 'selected';
		}

	    }

	}
    }
}

function filter_roadblocks(){
	projectId = document.getElementById('project_id').value;
	//creativeId = document.getElementById('creative_id').value;

	//ajax call
	values = 'action=filter&r_project_id=' + projectId + '&creative_id=' + creative_id;
	mod_roadblock(values,filter_roadblocks_callback);

}

function filter_roadblocks_callback(responseText){
	//alert(responseText);

	newDivHTML = responseText.substring(0, responseText.indexOf("{splitter}"));
	//hiddenDivHTML = responseText.substring(responseText.indexOf("{splitter}") + 10, responseText.length);
	hiddenDivHTML = responseText.substring(responseText.indexOf("{splitter}") + 10, responseText.indexOf("{new_creative}"));
	newRbHTML = responseText.substring(responseText.indexOf("{new_creative}") + 14, responseText.length);

	bodyDiv = document.getElementById('rb-list');
	hiddenDiv = document.getElementById('edit-roadblock-div');
	newRbDiv = document.getElementById('body-add-roadblock-nc');

	// add html to div
	bodyDiv.innerHTML = newDivHTML;
	hiddenDiv.innerHTML = hiddenDivHTML;
	newRbDiv.innerHTML = newRbHTML;

}

// INTERFACE SCRIPTS

// Get element X position
function getRealLeft(imgElem) {
    var xPos = imgElem.offsetLeft;
    var tempEl = imgElem.offsetParent;
    while (tempEl != null) {xPos += tempEl.offsetLeft;tempEl = tempEl.offsetParent;}
    return xPos;
}

function tz_getPageDims(){
    var tz_w,tz_h;if(self.innerHeight){tz_w = self.innerWidth;tz_h = self.innerHeight;} else if(document.documentElement && document.documentElement.clientHeight){tz_w = document.documentElement.clientWidth;tz_h = document.documentElement.clientHeight;} else if(document.body){tz_w=document.body.clientWidth;tz_h = document.body.clientHeight;} return Array(tz_w,tz_h);
}

function getRealTabsLeft() {
    var elm = document.getElementById('tabs-shell');
    winW = tz_getPageDims()[0];
    elmW = getRealWidth(elm);
    //alert(elm.style.left);
    //alert('winW: ' + winW + ': elmW: ' + elmW);
    return ((winW - elmW) / 2);
}

function getRealTabsBodyLeft() {
    var elm = document.getElementById('tabs-body');
    winW = tz_getPageDims()[0];
    elmW = getRealWidth(elm);
    //alert(elm.style.left);
    //alert('winW: ' + winW + ': elmW: ' + elmW);
    return ((winW - elmW) / 2);
}

// Get element Y position
function getRealTop(imgElem) {
    var yPos = imgElem.offsetTop;
    var tempEl = imgElem.offsetParent;
    while (tempEl != null) {yPos += tempEl.offsetTop;tempEl = tempEl.offsetParent;}
    return yPos;
}

// Get element width
function getRealWidth(imgElem) {
    var wVal = imgElem.offsetWidth;
    return wVal;
}

// Get element height
function getRealHeight(imgElem) {
    var hVal = imgElem.offsetHeight;
    return hVal;
}

//load preview content
function load_preview_content(me, creative_id, page){
    var elm = document.getElementById(me);
    elm.src=tabs_http_base+page+"/test_advert_main.phtml?creative_id="+creative_id;
}

// maximize preview iframe
function fit_preview_iframe(me, creative_id, page) {
    var elm = document.getElementById(me);
    var e = document.getElementById("creative-config-demo-url");
    if (typeof(e) != 'undefined' && e) {
		var eH = getRealHeight(e);
    }
    if(typeof(elm) != "undefined" && elm) {
		if (domtype == "mozilla" || domtype == "safari") {
			var winW = window.innerWidth;
			var winH = window.innerHeight;
			elm.style.height = (winH - eH) - 3 + 'px';
		}
		if (domtype == "msie") {
			if (ie_variant != 7) {
				var winW = document.body.offsetWidth;
				var winH = document.body.offsetHeight;
				elm.style.height = (winH - eH) - 5 + 'px';
			} else {
				var winW = document.body.offsetWidth;
				var winH = document.body.offsetHeight;
				// alert(winH);
				elm.style.height = (winH - eH) - 5 + 'px';
			}
		}
    }
    if(creative_id != null){
		window.setTimeout("load_preview_content('"+me+"','"+creative_id+"','"+page+"')",2000);
    }
}

//load preview content
function load_preview_content_roadblock(me, roadblock_id, project_id, page){
    var elm = document.getElementById(me);
    elm.src=tabs_http_base+page+"/test_advert_main.phtml?roadblock_id="+roadblock_id+"&project_id="+project_id;
}

function fit_preview_iframe_roadblock(me, roadblock_id, project_id, page){
    var elm = document.getElementById(me);
    var e = document.getElementById("creative-config-demo-url");
    if (typeof(e) != 'undefined' && e) {
		var eH = getRealHeight(e);
    }
    if(typeof(elm) != "undefined" && elm) {
		if (domtype == "mozilla" || domtype == "safari") {
			var winW = window.innerWidth;
			var winH = window.innerHeight;
			elm.style.height = (winH - eH) - 3 + 'px';
		}
		if (domtype == "msie") {
			if (ie_variant != 7) {
				var winW = document.body.offsetWidth;
				var winH = document.body.offsetHeight;
				elm.style.height = (winH - eH) - 5 + 'px';
			} else {
				var winW = document.body.offsetWidth;
				var winH = document.body.offsetHeight;
				// alert(winH);
				elm.style.height = (winH - eH) - 5 + 'px';
			}
		}
    }
    if(roadblock_id != null){
		window.setTimeout("load_preview_content_roadblock('"+me+"','"+roadblock_id+"','"+project_id+"','"+page+"')",2000);
    }
}

// get event position
function getRealPositionX(e) {
    var posx = 0;
    if (!e) var e = window.event;
    if (e.pageX) {
		posx = e.pageX;
		return posx;
    } else if (e.clientX) {
		posx = e.clientX;
		return posx;
    }
}

function getRealPositionY(e) {
    var posy = 0;
    if (!e) var e = window.event;
    if (e.pageY) {
		posy = e.pageY;
		return posy;
    } else if (e.clientY) {
		posy = e.clientY;
		return posy;
    }
}

// set initial variables for smooth div aperiance
var open_action_variable = new Array();
for(w=0;w<=20;w++) {
    open_action_variable[w] = 0;
 }
var h_up = new Array;
for(w=0;w<=20;w++) {
    h_up[w] = 0;
 }
var close_action_variable = new Array();
for(w=0;w<=20;w++) {
    close_action_variable[w] = 0;
 }
var h_down = new Array;
for(w=0;w<=20;w++) {
    h_down[w] = 0;
 }
var stop_here = new Array;
for(w=0;w<=20;w++) {
    stop_here[w] = 0;
 }
var h_up_extend = 0;
var h_down_extend = 0;
var id_up=0;
var id_down=0;
var h_up_x=0;
var h_down_x=0;
var id_up_x=0;
var id_down_x=0;
var count = 0;
var last_div = 0;
var last_header_className = 0;
var last_pos = 0;
var scroll = 'false';

// var unique = 0;
// global current tab
// this variable is updated with the toggle_tab() function

var current_tab = 1;

// smooth open and scroll positioning
function open_div(me, limit, scr){
    var unique = Math.floor(Math.random()*20+1);
    open_div_action(me, limit, scr, unique);
}

var snap = true;

function open_div_action(me, limit, scr, unique) {
    scroll = scr;
    h_up[unique]++;
    grow=30*h_up[unique];
    var elm_up = document.getElementById('body-'+me);
    var elm_parent = document.getElementById('tab-body');
    if (snap) {
		et = getRealTop(elm_up);
		eph = getRealHeight(elm_up.parentNode);
		if (elm_parent) {
			pst = elm_parent.scrollTop;
			ph = getRealHeight(elm_parent);
			pt = getRealTop(elm_parent);
			rh = (et - pt) - 50;
			d = ph - rh;
			if(scroll=='true'){
				elm_parent.scrollTop = rh;
			}
		}
		if(typeof(limit) != 'undefined' && limit && limit != '0' && limit != '') {
			elm_up.style.height = limit+'px';
			// alert(limit);
		}
    } else {

		elm_up.style.height=grow+"px";

		et = getRealTop(elm_up);
		eph = getRealHeight(elm_up.parentNode);
		if (elm_parent) {
			pst = elm_parent.scrollTop;
			ph = getRealHeight(elm_parent);
			pt = getRealTop(elm_parent);
			rh = (et - pt) - 50;
			d = ph - rh;
			if(scroll=='true'){
				elm_parent.scrollTop = rh;
			}
		}

		if (grow>=limit) {
			window.clearTimeout(open_action_variable[unique]);open_action_variable[unique]=0;h_up[unique]=0;scroll='false';
			if(typeof(limit) != 'undefined' && limit && limit != '0' && limit != '') {
				elm_up.style.height = limit+'px';
				// alert(limit);
			}
			// alert('pst:'+pst+', et:'+et+', et-pst='+(et-pst));
		} else {
			open_action_variable[unique] = window.setTimeout("open_div_action('"+me+"', '"+limit+"', '"+scr+"', '"+unique+"');",10);
		}
    }
}


// smooth close
function close_div(me, limit){
    if(typeof(limit) == 'undefined'){
		limit = 'auto';
    }
    var unique = Math.floor(Math.random()*20+1);
    close_div_action(me, limit, unique);
}

function close_div_action(me, limit, unique) {
    var elm_down = document.getElementById('body-'+me);

    close_action_variable[unique]=0;
    h_down[unique] = 0;
    if (limit=='auto'){
		elm_down.style.display = '';
    }
    if (me == 'navigation') {
		elm_down.style.display = 'none';
    }
    elm_down.style.height='auto';
}

// smooth open x axes

function open_div_x(me, limit_x){
    h_up_x++;
    grow_x=10*h_up_x;
    var elm_up_x = document.getElementById(me);
    elm_up_x.style.width=limit_x+"px";
    /*
	  if (snap) {
	  h_up_x=0;
	  } else {
	  elm_up_x.style.width=grow_x+"px";
	  if (grow_x>=limit_x) {
	  window.clearTimeout(id_up_x);id_up_x=0;h_up_x=0;
	  } else {
	  id_up_x = window.setTimeout("open_div_x('"+me+"', '"+limit_x+"');",20);
	  }
	  }
    */
}

// smooth close by x axes
function close_div_x(me){
    h_down_x++;
    grow_x=10*h_down_x;
    var elm_down_x = document.getElementById(me);
    var W = getRealWidth(elm_down_x);
    var shrink_x = W - h_down_x;

    if (snap) {
		elm_down_x.style.display='none';
		elm_down_x.style.width='180px';
    } else {
		if (shrink_x>=0){
			elm_down_x.style.width=shrink_x+"px";
		}
		if (shrink_x<=0){
			window.clearTimeout(id_down_x);id_down_x=0;h_down_x=0;
			elm_down_x.style.display='none';
			elm_down_x.style.width='180px';
		} else {
			id_down_x = window.setTimeout("close_div_x('"+me+"');",20);
		}
    }
}

// special function to handle add_new_project_via_client_level
function toggle_add_new_project(id) {
    var elm = document.getElementById('body-add-new-project-'+id);
    var elmParent = document.getElementById('body-'+id);
    var H = getRealHeight(elmParent);
    var h = getRealHeight(elm);
    var me = "add-new-project-"+id;
    if(elm.style.display == '') {
		elm.style.display = 'block';
		open_div(me, getRealHeight(elm), 'false');
		var unique = Math.floor(Math.random()*20+1);
		h_up[unique] = H/10;
		open_div_action(id, H + 110, 'false', unique);
		elmParent.style.height = 'auto';
		/*
		  if(domtype="mozilla"){
		  elmParent.style.height = getRealHeight(elmParent) + h + 20 + 'px';
		  }
		  if(domtype="msie"){
		  elmParent.style.height = getRealHeight(elmParent) + h + 90 + 'px';
		  }
		*/
    } else {
		close_div(id, H - h);
		close_div(me);
    }
}

// open if closed, close if opened, and close last opened
function toggle_div(me, scr) {
    var elm = document.getElementById('body-'+me);
    var elm_header = document.getElementById(me);
    if(last_div == me) {
		toggle_single_div(me);
		re_colour_list();
		if(elm.style.display != '') {
			elm_header.className = 'list-header-selected';
		}
		return false;
    }
    if (last_div != 0) {
		var lelm = document.getElementById('body-'+last_div);
		var lelm_header = document.getElementById(last_div);
		if (lelm_header) {
			lelm_header.className = last_header_className;
		}
		if (typeof(lelm) != 'undefined' && lelm && lelm.style.display == 'block') {
			lelm.style.height='auto';
			close_div(last_div);
			re_colour_list();
		}
    }
    if (typeof(elm) != 'undefined' && (elm.style.display == '' || elm.style.display == 'none')) {
		elm.style.height='auto';
		elm.style.display = 'block';

		last_header_className = elm_header.className;
		elm_header.className = 'list-header-selected';
		open_div(me, '', scr);
		last_div = me;
    }
}

// just toggle something
function toggle(me){
    var elm = document.getElementById(me);
    if(elm.style.display == '' || elm.style.display == 'none') {
		elm.style.display = 'block';
    } else {
		elm.style.display = 'none'

			}
}

function toggle_click_ints() {
    var elm = document.getElementById("creative-clicks-ints-timers");
    if(elm.style.display == '' || elm.style.display == 'none') {
		elm.style.display = 'block';
		$("#su-ev-btn img").attr("src","images/icon_dc_ci_on.gif");
    } else {
		elm.style.display = 'none';
		$("#su-ev-btn img").attr("src","images/icon_dc_ci.gif");
		//fullscreen - this is not a pretty hack but it's to correct the refresh failure once a user has gone from maximised screen to click-ints and then minimised
		if(domtype != 'msie' && domtype != 'safari') {
			document.getElementById('browseriframe').src = config_iframe_src;
		}
    }

}


function toggle_display_options() {
    var elm = document.getElementById('configure-utils');
    var belm = document.getElementById('creative-config-variables');
    if (document.getElementById('creative-clicks-ints-timers').style.display != 'block') {
		toggle('configure-utils');
		if(elm.style.display == 'none'){
			$("#su-do-btn img").attr("src", "images/icon_dc_do.gif");
		}else{
			$("#su-do-btn img").attr("src", "images/icon_dc_do_on.gif");
		}
		if ((floating || format_id=='1') && (document.getElementById("body-configure-utils").style.display == 'block')) {
			//toggle_move_mode();
		}

    }
    if(belm.style.display != 'block') {
		elm.style.display = 'none';
		$("#su-do-btn img").attr("src", "images/icon_dc_do.gif");
		if ((floating || format_id=='1') && (document.getElementById("body-configure-utils").style.display == 'block')) {
			toggle_move_mode();
		}
    }
}

// smooth jazz open and close single div
function toggle_single_div(me, limit){
    var elm = document.getElementById('body-'+me);
    var elmImg = document.getElementById('body-'+me+'-toggle');
    if(elm.style.display == '' || elm.style.display == 'none') {
		elm.style.display = 'block';
		if(typeof(limit) != 'undefined' && limit!='') {
			open_div(me, limit, 'false');
		} else {
			open_div(me, getRealHeight(elm), 'false');
		}
		if(typeof(elmImg) != 'undefined' && elmImg) {
			elmImg.src = 'images/icon_minus_orange.gif';
		}
    } else {
		close_div(me);
		if(elm.style.display = 'block'){
			elm.style.display = 'none'
				}
		if(typeof(elmImg) != 'undefined' && elmImg) {
			elmImg.src = 'images/icon_plus_orange.gif';
		}
    }
}

function toggle_single_div_block(me){
    var elm = document.getElementById('body-'+me);
    var elmImg = document.getElementById('body-'+me+'-toggle');
    if(elm.style.display == 'block') {
		elm.style.display = 'none';
		if(typeof(elmImg) != 'undefined' && elmImg) {
			elmImg.src = 'images/icon_plus_orange.gif';
		}
    } else {
		elm.style.display = 'block';
		if(typeof(elmImg) != 'undefined' && elmImg) {
			elmImg.src = 'images/icon_minus_orange.gif';
		}
    }
}

function toggle_tbody(me) {
    var elm = document.getElementById('body-'+me);
    if(elm.style.display == '') {
		elm.style.display = 'none';
    } else {
		elm.style.display = '';
    }
}

function scroll_div_down(div_id) {
    var d = document.getElementById(div_id);
    d.scrollTop=d.scrollHeight-d.clientHeight;
}

function show_test(src) {
    if (allow_previews) {
		elm = document.getElementById('body-creative-test');
		if(typeof(preview_iframe_src) != 'undefined' && preview_iframe_src) {
		    show_output();
		    show_data();

		    elm.style.display = 'block';
		    // clear out other iframe first
		    var configiframe = document.getElementById('browseriframe');
		    configiframe.src = "about:blank";

		    var myiframe = document.getElementById('browseriframe_test');
		    if (typeof(src) == "undefined"){
			src = preview_iframe_src;
		    }
		    myiframe.src = src + "&rnd=" + Math.random();
		    // document.getElementById('test-creative-img').src = "images/icon_minus_orange.gif";

		}
    }
}

function toggle_test() {
    elm = document.getElementById('body-creative-test');
    if (elm.style.display == 'block') {
	$("#tu-sp-btn img").attr("src","images/icon_dc_sp_on.gif");
	elm.style.display = 'none';
	hide_output();
    } else {
	$("#tu-sp-btn img").attr("src","images/icon_dc_sp.gif");

	//roadblock mode, dont refresh iframe
	//replication from show_test to resolve issue with send preview-roadblock synch error
	if(roadblock_mode) {

	    if (allow_previews) {
		elm = document.getElementById('body-creative-test');
		if(typeof(preview_iframe_src) != 'undefined' && preview_iframe_src) {
		    show_output();
		    show_data();

		    elm.style.display = 'block';
		    // clear out other iframe first
		    var configiframe = document.getElementById('browseriframe');
		    configiframe.src = "about:blank";

		    var myiframe = document.getElementById('browseriframe_test');
		    if (typeof(src) == "undefined"){
			src = preview_iframe_src;
		    }
		}
	    }

	} else {
	    //not in roadblock mode, refresh iframe
	    show_test();
	}

    }
}

function popup_test() {
    //window.open(preview_iframe_src, "Test Window", "height = 600, width = 800");
    //window.open(preview_iframe_src);
    var popup_src = tabs_http_base + "creative/test_advert.phtml?creative_id=" + creative_id;
    //window.open(popup_src, "Test Window", "width = 800");

    window.open(popup_src);

}

////////////////////////////////////// fullscreen for test functions
var fullscreen_tab_four = false;

function toggle_fullscreen_four() {

	if(fullscreen_tab_four) {
		//minimised
		fullscreen_tab_four = false;

	} else {
		//maximised
		fullscreen_tab_four = true;
	}
	setup_fullscreen_four();
}

function setup_fullscreen_four() {

	if(fullscreen_tab_four) {
		$("#tu-fs-btn img").attr("src","images/icon_dc_mm_on.gif");

		//setting sizes
		var theSizes = new Array();
		theSizes = tz_getPageDims();
		var width = theSizes[0];
		var height = theSizes[1];

		//new variable for setting
		//var heightIframe = (height - 60) + 'px';

		if(domtype == 'msie') {

			var ieTable = (width) + 'px';

			if(ie_variant == 7) {

				var ieIframe = (height - 60) + 'px';
				var ieBody = (height) + 'px';
				var ie7Shell = (width) + 'px';

				document.getElementById('tabs-shell').style.width = ie7Shell;
				$("#tabs-shell").css("margin-left",0);
			} else {
				var ieIframe = (height - 60) + 'px';
				var ieBody = (height) + 'px';
			}

			document.getElementById('tabs-body').setAttribute('className','tabs-body-max');
			document.getElementById('tab-body').setAttribute('className','tab-body-dc-max');
			document.getElementById('creative-title-dc').setAttribute('className','creative-title-dc-max');

			document.getElementById('table-test').style.width = ieTable;
			document.getElementById('browseriframe_test').style.height = ieIframe;
			document.getElementById('tab-body').style.height = ieBody;
			document.getElementById('browserdiv_test').style.height = ieIframe;

		} else if(domtype == 'safari') {

			var sfIframe = (height - 60) + 'px';
			var sfBody = (height) + 'px';
			var sfShell = '100%';
			var sfTable = width + 'px';

			document.getElementById('tab-body').setAttribute('class','tab-body-dc-max');
			document.getElementById('tabs-body').setAttribute('class','tabs-body-max');
			document.getElementById('creative-title-dc').setAttribute('class','creative-title-dc-max');

			document.getElementById('tabs-shell').style.width = sfShell;
			$("#tabs-shell").css("left",0);
			document.getElementById('browserdiv_test').style.height = sfIframe;
			document.getElementById('table-test').style.width = sfTable;
			document.getElementById('browseriframe_test').style.height = sfIframe;
			document.getElementById('tab-body').style.height = sfBody;

			//cover the updating of the iframe
			cover_updating(width, height);

			//refresh in safari
			if(!roadblock_mode){
			    document.getElementById('browseriframe_test').src = preview_iframe_src + "&rnd=" + Math.random();
			}

		} else {
			$(document.body).css('width', width);
			var ffTitle = (width - 15 ) + 'px';
			var ffTable = width + 'px';
			var ffIframe = (height - 61) + 'px';
			var ffBody = (height) + 'px';

			//cover the updating of the iframe
			cover_updating(width, height);

			document.getElementById('creative-title-dc').style.width = ffTitle;
			document.getElementById('table-test').style.width = ffTable;
			document.getElementById('browseriframe_test').style.height = ffIframe;
			document.getElementById('browserdiv_test').style.height = ffIframe;
			document.getElementById('tab-body').style.height = ffBody;

			document.getElementById('tab-body').setAttribute('class','tab-body-dc-max');
			document.getElementById('tabs-body').setAttribute('class','tabs-body-max');
			document.getElementById('creative-title-dc').setAttribute('class','creative-title-dc-max');
		}

		full_hide_four(height);
		browser_min_max_four();

	} else {

		if(domtype == 'msie') {
			document.getElementById('tabs-body').setAttribute('className','tabs-body');
			document.getElementById('tab-body').setAttribute('className','tab-body-dc');
			document.getElementById('creative-title-dc').setAttribute('className','');

			if(ie_variant == 7) {
				//solves IE7 specific problem
				document.getElementById('tabs-shell').style.width = 'auto';
				/*$("#tabs-shell").css("margin-left",-21);*/
			}

		} else if(domtype == 'safari') {

			document.getElementById('tabs-shell').style.width = 'auto';
			$("#tabs-shell").css("left","");
			document.getElementById('tabs-body').setAttribute('class','tabs-body');
			document.getElementById('tab-body').setAttribute('class','tab-body-dc');
			document.getElementById('creative-title-dc').setAttribute('class','');
			hide_nav_update();
			//shadow ends up out of place if you dont specify the width of it
			document.getElementById('tabs-shadow').style.width = '880px';

			//cover the iframe whilst restoring
			cover_restore();
			if(!roadblock_mode){
			    document.getElementById('browseriframe_test').src = preview_iframe_src + "&rnd=" + Math.random();
			}

		} else {
			//firefox part
			//cover the updating of the iframe
			$(document.body).css('width', '840px');
			cover_restore();

			document.getElementById('tabs-body').setAttribute('class','tabs-body');
			document.getElementById('tab-body').setAttribute('class','tab-body-dc');
			document.getElementById('creative-title-dc').setAttribute('class','');
			document.getElementById('tabs-shadow').style.width = '880px';
			hide_nav_update();
		}

		full_restore_four();
		browser_min_max_four();

	}
}

//hides layers to enable fullscreen view
function full_hide_four(height) {
    document.getElementById('show-hide-nav').style.display = 'none';
    document.getElementById('show-hide-nav-img').style.display = 'none';
    hide_nav();

    document.getElementById('table-test').cellSpacing = '0px';
    document.getElementById('td-body').style.height = 'auto';
    document.getElementById('tabs-shell').style.top = '0px';

    //new line test variable
    //document.getElementById('browserdiv_test').style.height = height + 'px';

	if(domtype == 'safari'){
		document.getElementById('tabs-logo').style.display = 'none';
		document.getElementById('tabs-header-corner').style.display = 'none';
		document.getElementById('tabs-tz-logo').style.display = 'none';
		document.getElementById('tabs-login-info').style.display = 'none';

		document.getElementById('tabs-header').style.width = '0px';
		document.getElementById('tabs-header').style.height = '0px';
	}else{
		document.getElementById('tabs-header').style.display = 'none';
	}

	//document.getElementById('tabs-header').style.display = 'none';
	document.getElementById('tabs-dc').style.display = 'none';
	document.getElementById('tabs-footer').style.display = 'none';
	document.getElementById('tabs-shadow').style.display = 'none';
	document.getElementById('tabs-shadowpng').style.display = 'none';

	//internal-info only shows for internal users
	if(document.getElementById('internal-info')){
	    document.getElementById('internal-info').style.display = 'none';
	}
	
	document.getElementById('dc-footer').style.display = 'none';

	//hidden jump function
	if(document.getElementById('jump-hidden')){
	    document.getElementById('jump-hidden').style.display = 'block';
	}
}

//restores normal TABS values
function full_restore_four() {

	$("#tu-fs-btn img").attr("src","images/icon_dc_mm.gif");


	document.getElementById('creative-title-dc').style.width = 'auto';
	document.getElementById('table-test').style.width = '838px';
	document.getElementById('browseriframe_test').style.height = '422px';
	document.getElementById('tab-body').style.height = '520px';
	document.getElementById('show-hide-nav').style.display = 'block';
	document.getElementById('show-hide-nav-img').style.display = 'block';
	document.getElementById('table-test').cellSpacing = '5px';
	document.getElementById('td-body').style.height = '510px';
	document.getElementById('tabs-shell').style.top = '5px';

	document.getElementById('tabs-dc').style.display = 'block';
	document.getElementById('tabs-footer').style.display = 'block';
	document.getElementById('tabs-shadow').style.display = 'block';
	document.getElementById('tabs-shadowpng').style.display = 'block';

	//internal-info only shows for internal users
	if(document.getElementById('internal-info')){
	    document.getElementById('internal-info').style.display = 'block';
	}

	document.getElementById('dc-footer').style.display = 'block';

	//hidden jump function
	if(document.getElementById('jump-hidden')){
	    document.getElementById('jump-hidden').style.display = 'none';
	}

	//new line test variable
	document.getElementById('browserdiv_test').style.height = '422px';

	if(domtype == 'safari'){
		document.getElementById('tabs-logo').style.display = 'block';
		document.getElementById('tabs-header-corner').style.display = 'block';
		document.getElementById('tabs-tz-logo').style.display = 'block';
		document.getElementById('tabs-login-info').style.display = 'block';
		document.getElementById('tabs-header').style.width = '840px';
		document.getElementById('tabs-header').style.height = '57px';
	}else{
		document.getElementById('tabs-header').style.display = 'block';
	}

	//in safari, despite the below line, the header doesn't display again
	//document.getElementById('tabs-header').style.display = 'block';
}

//some browser things to update iframe in different browsers
function browser_min_max_four() {

    if(domtype == 'msie') {
	fix_shadow();
	//do not refresh in roadblock mode as x and y are set, in single view ad should be centred and so refresh necessary
	if(ie_variant == 7 && !roadblock_mode){
	    document.getElementById('browseriframe_test').src = preview_iframe_src + "&rnd=" + Math.random();
	}
    } else if(domtype == 'safari') {
	if(!roadblock_mode){
	    fix_shadow();
	}
    } else {
	if(!roadblock_mode){
	    document.getElementById('browseriframe_test').src = preview_iframe_src + "&rnd=" + Math.random();
	}
    }
}

function hide_loading_indicator_four(){
    var shell = document.getElementById('tabs-shell');
    var shadowpng = document.getElementById('tabs-shadowpng');
    var loading = document.getElementById('tabs-loading');
    shell.style.display = 'block';
    shadowpng.style.display ='block';
    loading.style.display = 'none';
}

function cover_updating(width, height){
	var ref = tz_get_iframe_content('browseriframe_test');

	if(ref.getElementById('configurediv')){
		ref.getElementById('configurediv').style.visibility='visible';
		var ref2 = ref.getElementById('tz_message');
		ref2.style.width = width + 'px';
		ref2.style.height = height + 'px';
	}
	}

function cover_restore(){
	var ref = tz_get_iframe_content('browseriframe_test');

	if(ref.getElementById('configurediv')){
		ref.getElementById('configurediv').style.visibility='visible';
		var ref2 = ref.getElementById('tz_message');
		ref2.style.width = '807px';
		ref2.style.height = '422px';
	}
}

function toggle_dfa_preview_mode(){
    
    var exiting_rb_mode = false;

    if(dfa_preview_mode){
	// changing to TZ preview mode

	$("#event_output").height(150);
	$("#event_output").width(300);
	$("#output_body").height($("#event_output").height()-$("#eo-resize-handle").height()-$("#output_header").height());

	if(roadblock_mode) {
	    // switch off roadblock then change to TZ preview
	    toggle_roadblock_iframe();
	    exiting_rb_mode = true;
	    $("#dfa-test-preview img").attr("src", "images/icon_dc_dfa_on.gif");
	    
	} else {
	    $("#dfa-test-preview img").attr("src", "images/icon_dc_dfa.gif");

	    url_value = document.getElementById('config_url').value;
	    $("#browseriframe_test").attr("src", tabs_http_base + 'creative/test_advert_main.phtml?config_mode=false&creative_id=' + creative_id + '&override_url=' + escape(url_value));
	    $("#edit-options-dc-test").show();
	} 
	
    } else {
	// changing to DFA preview 

        $("#event_output").height(450);
        $("#event_output").width(350);
        $("#output_body").height($("#event_output").height()-$("#eo-resize-handle").height()-$("#output_header").height());

	if(roadblock_mode){
	    // switch off roadblock mode then because we came from DFA mode, return to DFA preview
	    toggle_roadblock_iframe();
	}
	$("#dfa-test-preview img").attr("src", "images/icon_dc_dfa_on.gif");

	$("#browseriframe_test").attr("src", tabs_http_base + 'creative/dfa_preview_generator.php?creative_id=' + creative_id);
	$("#edit-options-dc-test").hide();
    }
    
    $("#output_body").empty();
    //if in tabs preview switch to dfa and vice versa
    if (!exiting_rb_mode) {
	dfa_preview_mode = dfa_preview_mode ? dfa_preview_mode = false : dfa_preview_mode = true;
    }
}

////////////////////////////////////// fullscreen functions

var fullscreen_test_mode = false;

function toggle_fullscreen() {
	if(fullscreen_test_mode) {
		fullscreen_test_mode = false;
	} else {
		fullscreen_test_mode = true;
	}
	setup_fullscreen();
}

function check_fullscreen() {

	if(fullscreen_test_mode){
		setup_fullscreen();
	} else if (fullscreen_tab_four){
		setup_fullscreen_four();
	}
}

function setup_fullscreen() {
	$("#su-fs-btn img").attr("src","images/icon_dc_mm_on.gif");

    if (fullscreen_test_mode) {
	//setting sizes
	var theSizes = new Array();
	theSizes = tz_getPageDims();
	var width = theSizes[0];
	var height = theSizes[1];
	//new variable for setting
	var heightIframe = (height - 60) + 'px';
    	if(domtype == 'msie') {
	    var ieTable = (width) + 'px';
	    if(ie_variant == 7) {
		//var ieIframe = (height - 60) + 'px';
		var ieBody = (height) + 'px';
		var ie7Shell = (width) + 'px';
		document.getElementById('tabs-shell').style.width = ie7Shell;
		$("#tabs-shell").css("margin-left",0);
	    } else {
		//var ieIframe = (height - 60) + 'px';
		var ieBody = (height) + 'px';
	    }
    	    document.getElementById('tabs-body').setAttribute('className','tabs-body-max');
	    document.getElementById('tab-body').setAttribute('className','tab-body-dc-max');
    	    document.getElementById('creative-title-dc').setAttribute('className','creative-title-dc-max');
	    document.getElementById('table-test').style.width = ieTable;
    	    //document.getElementById('browseriframe').style.height = ieIframe;
	    document.getElementById('tab-body').style.height = ieBody;
    	} else if(domtype == 'safari') {

	    var sfTable = width + 'px';
	    var sfIframe = (height - 60) + 'px';
	    var sfBody = (height) + 'px';
	    var sfShell = '100%';
	    document.getElementById('tabs-shell').style.width = sfShell;
	    $("#tabs-shell").css("left",0);
	    document.getElementById('tab-body').setAttribute('class','tab-body-dc-max');
	    document.getElementById('tabs-body').setAttribute('class','tabs-body-max');
	    document.getElementById('creative-title-dc').setAttribute('class','creative-title-dc-max');
	    ////////document.getElementById('creative-title-dc').style.width = sfTitle;
	    document.getElementById('table-test').style.width = sfTable;
	    document.getElementById('browseriframe').style.height = sfIframe;
	    document.getElementById('tab-body').style.height = sfBody;

	    var ref = tz_get_iframe_content('browseriframe');
	    if(ref.getElementById('configurediv')){
		ref.getElementById('configurediv').style.visibility='visible';
		var ref2 = ref.getElementById('tz_message');
		ref2.style.width = width + 'px';
		ref2.style.height = height + 'px';
	    }

	} else {

	    $(document.body).css('width', width);
	    //firefox part, this is where to cover the loading of the iframe
	    var ref = tz_get_iframe_content('browseriframe');
	    if (ref.getElementById('configurediv')){
		ref.getElementById('configurediv').style.visibility='visible';
		var ref2 = ref.getElementById('tz_message');
		ref2.style.width = width + 'px';
		ref2.style.height = height + 'px';
	    }
	    var ffTitle = (width - 15 ) + 'px';
	    var ffTable = width + 'px';
	    //var ffIframe = (height - 60) + 'px';
	    var ffBody = (height) + 'px';
	    document.getElementById('tab-body').setAttribute('class','tab-body-dc-max');
	    document.getElementById('tabs-body').setAttribute('class','tabs-body-max');
	    document.getElementById('creative-title-dc').setAttribute('class','creative-title-dc-max');
	    document.getElementById('creative-title-dc').style.width = ffTitle;
	    document.getElementById('table-test').style.width = ffTable;
	    document.getElementById('tab-body').style.height = ffBody;
	}

	if(roadblock_mode){
	    document.getElementById('roadblockiframe').style.height = heightIframe;
	    document.getElementById('browseriframe').style.height = heightIframe;
	} else {
	    document.getElementById('browseriframe').style.height = heightIframe;
	    if(typeof(default_roadblock) != 'undefined'){
		document.getElementById('roadblockiframe').style.height = heightIframe;
	    }
	}

	full_hide(height);
	browser_min_max();

	//set src of iframe
	if(divthree){
	    //refresh_config_iframe();
	    document.getElementById('browseriframe').src = config_iframe_src;
	}else if(divfour){
	    document.getElementById('browseriframe_test').src = config_iframe_src;
	}

    } else {

	if(domtype == 'msie') {
	    document.getElementById('tabs-body').setAttribute('className','tabs-body');
	    document.getElementById('tab-body').setAttribute('className','tab-body-dc');
    	    document.getElementById('creative-title-dc').setAttribute('className','');
	    if(ie_variant == 7) {
		//solves IE7 specific problem
		document.getElementById('tabs-shell').style.width = 'auto';
		/* $("#tabs-shell").css("margin-left",-21); */
	    }
	}
	    else if(domtype == 'safari') {
		document.getElementById('browseriframe').src = '';
		document.getElementById('tabs-shell').style.width = 'auto';
		$("#tabs-shell").css("left","");
		document.getElementById('tabs-body').setAttribute('class','tabs-body');
		document.getElementById('tab-body').setAttribute('class','tab-body-dc');
		document.getElementById('creative-title-dc').setAttribute('class','');
		hide_nav_update();
		//shadow ends up out of place if you dont specify the width of it
		document.getElementById('tabs-shadow').style.width = '880px';
		var ref = tz_get_iframe_content('browseriframe');
		if(ref.getElementById('configurediv')){
		    ref.getElementById('configurediv').style.visibility='visible';
		    var ref2 = ref.getElementById('tz_message');
		    ref2.style.width= '790px';
		    ref2.style.height= '410px';
		}

	    } else {
		//below part to cover the updating of the iframe
			var ref = tz_get_iframe_content('browseriframe');
			if(ref.getElementById('configurediv')){
			    ref.getElementById('configurediv').style.visibility='visible';
			    var ref2 = ref.getElementById('tz_message');
			    ref2.style.width= '790px';
			    ref2.style.height= '410px'
				}
			//when the browser isn't IE or safari, atm only FF
			$(document.body).css('width', '840px');
			document.getElementById('tabs-body').setAttribute('class','tabs-body');
			document.getElementById('tab-body').setAttribute('class','tab-body-dc');
			document.getElementById('creative-title-dc').setAttribute('class','');
			document.getElementById('tabs-shadow').style.width = '880px';
			hide_nav_update();
		}

		full_restore();
		browser_min_max();

		//set src of iframe
		document.getElementById('browseriframe').src = config_iframe_src;

		if(divfour){
			var ref = tz_get_iframe_content('browseriframe_test');

			ref.getElementById('configurediv').style.visibility='hidden';
			var ref2 = ref.getElementById('tz_message');

			ref2.style.width = '0px';
			ref2.style.height = '0px';
			document.getElementById('browseriframe_test').src = config_iframe_src;
		}

	}

}

//hides layers to enable fullscreen view
function full_hide(height) {

    //start - roadblock mode requires these changes
    var heightIframe = (height - 60) + 'px';
    document.getElementById('browseriframe').style.height = heightIframe;

    if(roadblock_mode){
		document.getElementById('roadblockiframe').style.height = heightIframe;
		document.getElementById('browseriframe').style.height = heightIframe;
    } else {
		document.getElementById('browseriframe').style.height = heightIframe;

		if(typeof(default_roadblock) != 'undefined'){
			document.getElementById('roadblockiframe').style.height = heightIframe;
		}

    }
    //end - roadblock mode changes

    document.getElementById('show-hide-nav').style.display = 'none';
    document.getElementById('show-hide-nav-img').style.display = 'none';
    hide_nav();

    //try to correct bug
    hide_nav();

    document.getElementById('creative-clicks-ints-timers').style.height = (height - 60) + 'px';
    document.getElementById('project-publish-margin-div').style.height = (height - 92) + 'px';

    document.getElementById('table-test').cellSpacing = '0px';
    document.getElementById('td-body').style.height = 'auto';
    document.getElementById('tabs-shell').style.top = '0px';
    document.getElementById('creative-config-variables').style.border = '0px';

    //new line test variable
    //document.getElementById('browserdiv_test').style.height = height + 'px';

    if(domtype == 'safari'){

	document.getElementById('tabs-logo').style.display = 'none';
	document.getElementById('tabs-header-corner').style.display = 'none';
	document.getElementById('tabs-tz-logo').style.display = 'none';
	document.getElementById('tabs-login-info').style.display = 'none';

	document.getElementById('tabs-header').style.width = '0px';
	document.getElementById('tabs-header').style.height = '0px';

    }else{
	document.getElementById('tabs-header').style.display = 'none';
    }

    //document.getElementById('tabs-header').style.display = 'none';
    document.getElementById('tabs-dc').style.display = 'none';
    document.getElementById('tabs-footer').style.display = 'none';
    document.getElementById('tabs-shadow').style.display = 'none';
    document.getElementById('tabs-shadowpng').style.display = 'none';

    //internal-info only shows for internal users
    if(document.getElementById('internal-info')){
	document.getElementById('internal-info').style.display = 'none';
    }

    document.getElementById('dc-footer').style.display = 'none';
}

//restores normal TABS values
function full_restore() {

    $("#su-fs-btn img").attr("src","images/icon_dc_mm.gif");

	document.getElementById('creative-title-dc').style.width = 'auto';
	document.getElementById('table-test').style.width = '838px';
	document.getElementById('browseriframe').style.height = '422px';
	document.getElementById('tab-body').style.height = '520px';
	document.getElementById('creative-clicks-ints-timers').style.height = '447px';
	document.getElementById('project-publish-margin-div').style.height = '415px';
	document.getElementById('show-hide-nav').style.display = 'block';
	document.getElementById('show-hide-nav-img').style.display = 'block';
	document.getElementById('table-test').cellSpacing = '5px';
	document.getElementById('td-body').style.height = '510px';
	document.getElementById('tabs-shell').style.top = '5px';
	document.getElementById('creative-config-variables').style.border = '1px #FFD6C9 solid';
	document.getElementById('tabs-dc').style.display = 'block';
	document.getElementById('tabs-footer').style.display = 'block';
	document.getElementById('tabs-shadow').style.display = 'block';
	document.getElementById('tabs-shadowpng').style.display = 'block';
	
	//internal-info only shows for internal users
	if(document.getElementById('internal-info')){
	    document.getElementById('internal-info').style.display = 'block';
	}

	document.getElementById('dc-footer').style.display = 'block';

	if(roadblock_mode){
		document.getElementById('roadblockiframe').style.height = '422px';
	} else {

		if(typeof(default_roadblock) != 'undefined'){
			document.getElementById('roadblockiframe').style.height = '422px';;
		}
	}

	//new line test variable
	document.getElementById('browserdiv_test').style.height = '422px';

	if(domtype == 'safari'){
		document.getElementById('tabs-logo').style.display = 'block';
		document.getElementById('tabs-header-corner').style.display = 'block';
		document.getElementById('tabs-tz-logo').style.display = 'block';
		document.getElementById('tabs-login-info').style.display = 'block';
		document.getElementById('tabs-header').style.width = '840px';
		document.getElementById('tabs-header').style.height = '57px';
	}else{
		document.getElementById('tabs-header').style.display = 'block';
	}

	//in safari, despite the below line, the header doesn't display again
	//document.getElementById('tabs-header').style.display = 'block';
}

//some browser things to update iframe in different browsers
function browser_min_max() {

	if(domtype == 'msie') {
		fix_shadow();
		if(ie_variant == 7){
		    document.getElementById('browseriframe').src = config_iframe_src;
		}
	} else if(domtype == 'safari') {
	    fix_shadow();
	} else {
		//refresh the iframe to centre the creative
		document.getElementById('browseriframe').src = config_iframe_src;
	}
}

function hide_loading_indicator(){
    var shell = document.getElementById('tabs-shell');
    var shadowpng = document.getElementById('tabs-shadowpng');
    var loading = document.getElementById('tabs-loading');
    shell.style.display = 'block';
    shadowpng.style.display ='block';
    loading.style.display = 'none';
}

//////////////////////////////////////// end fullscreen stuff


function toggle_send_preview() {
    elm = document.getElementById('body-send-preview');
    if (elm.style.display == 'block') {
		elm.style.display = 'none';
		document.getElementById('send-preview-img').src = "images/icon_plus_orange.gif";
    } else {
		elm.style.display = 'block';
		document.getElementById('send-preview-img').src = "images/icon_minus_orange.gif";
    }
}

function toggle_configure() {
    elm = document.getElementById('body-creative-config');
    if (elm.style.display == 'block') {
		hide_configure('creative-config');
    } else {
		show_configure('creative-config');
    }

}

// tab selector function
var allow_previews = true;
function toggle_tab(show_tab_id, num_tabs) {
    var allow = false;
    if (typeof(avail_tabs) != 'undefined' && avail_tabs) {
		for (var i=0; i<avail_tabs.length; i++) {
			if (avail_tabs[i] == show_tab_id) {
				allow = true;
			}
		}
    } else {
		allow = true;
    }
    if(allow) {
		for(var i=1;i<=num_tabs;i++){
			var elm = document.getElementById('tab'+i);
			if (elm.className != 'disabled') {
				var helpbody = document.getElementById('context-help-body-'+i);
				var elmbody = document.getElementById('tab-body-'+i);
				var stepsImg = document.getElementById('step'+i);
				var footer = document.getElementById('footer'+i);
				if(i != show_tab_id){
					// unset the tab
					elm.className='';
					elmbody.style.display = 'none';
					// unset context help div
					if(typeof(helpbody) != 'undefined' && helpbody) {
						helpbody.style.display = 'none';
					}
					// unset step image
					if(typeof(stepsImg) != 'undefined' && stepsImg) {
						stepsImg.src = 'images/step'+i+'_off.gif';
					}
					// unset dc footer with buttons
					if(typeof(footer) != 'undefined' && footer) {
						footer.className='dc-footer-hide';
					}
				} else {
					// set tab
					current_tab = i;
					elm.className='here';
					elmbody.style.display='block';
					// set context help div
					if(typeof(helpbody) != 'undefined' && helpbody) {
						helpbody.style.display = 'block';
					}
					// set step image
					if(typeof(stepsImg) != 'undefined' && stepsImg) {
						stepsImg.src = 'images/step'+i+'_on.gif';
					}
					// set dc footer with buttons
					if(typeof(footer) != 'undefined' && footer) {
						footer.className='dc-footer-show';
					}
				}
			}
		}
    } else {
		allow_previews = false;
    }
}
var config_iframe_loaded = false;
var settings_changed = false;
var files_changed = false;

var dc_timer;
var file_mtime = 0;

function runner_callback(responseText) {

	//uncomment below to restore
	if(responseText != "0" && responseText != "") {

		//if(document.getElementById('data_body')){
		//clear_data();
		//}

		//do stuff with response string here
		var response_array = responseText.split("#SPLIT#");
		var dc_time = response_array[0];
		file_mtime = dc_time;
		var td_colour = "odd";

		var response_vars = response_array[1].split("\n");
		var head_array = response_vars[0].split("#COMMA#");

		show_dc = true;
		if(document.getElementById('data-body')){
			clear_data();
		}
		report_data("");

		var theTable = document.createElement("table");
		var newBody = document.createElement("tbody");
		var newRow = document.createElement("tr");
		var rowArray = new Array();

		for(i=0;i<head_array.length;i++){

			var newCell = document.createElement("th");
			newCell.appendChild(document.createTextNode(head_array[i]));
			newRow.appendChild(newCell);
		}

		newBody.appendChild(newRow);

		for(b=1;b<response_vars.length;b++){

			//elements are separated by #COMMA#
			var values_array = response_vars[b].split("#COMMA#");

			if(domtype == 'msie'){
				var newRow1 = document.createElement("<tr class='"+td_colour+"'>");
			} else {
				var newRow1 = document.createElement("tr");
				newRow1.setAttribute("class",td_colour);
			}

			if(td_colour == "even") {
				td_colour = "odd";
			} else if(td_colour == "odd") {
				td_colour="even";
			}

			for(a=0;a<values_array.length;a++){
				var newCell1 = document.createElement("td");

				newCell1.appendChild(document.createTextNode(values_array[a]));
				newRow1.appendChild(newCell1);

				//add rows to array
				rowArray.push(newRow1);

			}

		}

		//reverse the rows before adding them to table body
		rowArray.reverse();

		for(w=0;w<rowArray.length;w++){
			newBody.appendChild(rowArray[w]);
		}

		theTable.appendChild(newBody);
		document.getElementById('data-body').appendChild(theTable);

	}

}

function dc_runner_start() {
	dc_timer = setTimeout("dc_runner_start()",10000);
	loadXMLDoc(tabs_http_base + 'creative/tz_dc_check.phtml', 'creative_id=' + creative_id + '&mtime=' + file_mtime, runner_callback);
	//report_data("runner started - initial value:" + file_mtime);
}

function dc_runner_stop() {
	clearTimeout(dc_timer);
	//report_data("runner deactivated");
}


var divloaded = false;

//roadblock variable
var divthree = false;
var divfour = false;

function toggle_delivery_tab(show_tab_id, num_tabs) {

    //clear the preview area so that it doesnt keep on playing in IE7
    if(show_tab_id != 2) {
		document.getElementById("resource-preview").innerHTML = "<div class='dc-body-margin'><img src='"+tabs_http_base+"images/preview_holder.jpg' width='200' height='200' /></div>";
    }

	// clear out config and test iframes, so they don't keep playing
	reset_preview_iframes();


	// reset move mode variable if setup tab not selected AND display options panel is NOT open
	if(show_tab_id!=3) {
		in_move_mode = false;
	}

    // only show click/int/data capture output on test tab
    if (show_tab_id != 4) {
		hide_output();
		hide_data();
    }

    // get tab specific utilities buttons
    var su = document.getElementById('setup-utilities');
    var tu = document.getElementById('test-utilities');

    // get help div to check if visible
    var ch = document.getElementById('body-context-help');
    var cu = document.getElementById('configure-utils');

    // if config iframe has been loaded but user goes to another tab then reload the iframe to prevent duplicate ads
    if (config_iframe_loaded && show_tab_id == 3) {
		refresh_config_iframe();
    }

    if ( (show_tab_id == 5 && (settings_changed || files_changed)) || (settings_changed && (show_tab_id == 2 || show_tab_id == 4 || show_tab_id == 7)) ) {
		show_loading_indicator();
		var new_url = tabs_http_base + "creative/delivery.phtml?creative_id=" + creative_id + "&tab=" + show_tab_id;
		document.location.href = new_url;
		return;
    } else {
		if (cu.style.display == 'block') {
			toggle_display_options();
		}
		if (su.style.display == 'block') {
			toggle('setup-utilities');
		}
		if (tu.style.display == 'block') {
			toggle('test-utilities');
		}
		// $('#roadblock_config').hide();

		toggle_tab(show_tab_id, num_tabs);
		if (show_tab_id == 3) {
			//roadblock variable
			divthree = true;
			divfour = false;

			if (allow_previews) {
				if (files_changed) {
					show_loading_indicator();
					var new_url = tabs_http_base + "creative/delivery.phtml?creative_id=" + creative_id + "&tab=3";
					document.location.href = new_url;
					return;
				} else {
					if (ch.style.display != 'block') {
						hide_nav();
					}
					if (!config_iframe_loaded) {
						refresh_config_iframe();
						config_iframe_loaded = true;
					}
					//show_click_warning();
					toggle('setup-utilities');
				}

				if (tu.style.display == 'block') {
					toggle('test-utilities');
				}
				if (cu.style.display == 'none') {
					toggle_display_options();
				}

				//fix for safari
				if(domtype == 'safari' && roadblock_mode){
					//document.getElementById('browseriframe').style.display = "none";
					$("#browseriframe").css("display","none");
				}
				//if ($("#roadblockiframe").css("display") == "block"){
				//$("#roadblock_config").show();
				//$("#configure-utils").hide();
				//}

				toggle_tab(show_tab_id, num_tabs);

				/*
				  if (show_tab_id == 3) {
				  if (allow_previews) {
				  if (files_changed) {
				  var new_url = tabs_http_base + "creative/delivery.phtml?creative_id=" + creative_id + "&tab=3";
				  document.location.href = new_url;
				  return;
				  } else {
				  if (ch.style.display != 'block') {
				  hide_nav();
				  }
				  if (!config_iframe_loaded) {
				  refresh_config_iframe();
				  config_iframe_loaded = true;
				  }
				  //show_click_warning();
				  toggle('setup-utilities');
				  }
				  }
				  if (cu.style.display == 'none') {
				  toggle_display_options();
				  }
				*/
				if(typeof(from_fix)!='undefined' && from_fix) {
					toggle_display_options();
				}
			}
		} else if (show_tab_id == 4) {
			//indicates what frame is refreshing for covering the updating of iframes in firefox
			divthree = false;
			divfour = true;

			if (creative_published_from_dc) {
				show_loading_indicator();
				var new_url = tabs_http_base + "creative/delivery.phtml?creative_id=" + creative_id + "&tab=4";
				document.location.href = new_url;
				return;
			}
			if (allow_previews) {
				if (ch.style.display != 'block') {
					hide_nav();
				}
				//show_output();
				if (document.getElementById('send-preview').style.display != "block") {

					//swapped row below this for a boolean as safari doesnt understand it
					//if ($("#roadblockiframe").css("display") == "block"){
					//if ($("#roadblockiframe").style("display") == "block"){
					if (typeof roadblock_mode != "undefined" && roadblock_mode) {
						var mode = roadblock_iframe_src.split("mode=")[1].split('&')[0];
						var before_mode = roadblock_iframe_src.split("mode=")[0];
						var after_mode = roadblock_iframe_src.split("mode=")[1].split('&');
						after_mode[0] = undefined;

						roadblock_iframe_src_test = before_mode + "mode=test" + after_mode.join('&');
						show_test(roadblock_iframe_src_test);
					}
					else{
						show_test();
					}
				}
                if(dfa_preview_mode) {$("#edit-options-dc-test").hide();}
				toggle('test-utilities');
			}


		} else if (show_tab_id==5) {
			loopCheckboxes(dc_project_id);
		} else if (show_tab_id==6 && creative_approved_in_session){
			show_loading_indicator();
			var new_url = tabs_http_base + "creative/delivery.phtml?creative_id=" + creative_id + "&tab=6";
			document.location.href = new_url;
			return;
		}
		//toggle_tab(show_tab_id, num_tabs);
    }

    //start playing/displaying latest selected resource
    if(show_tab_id == 2  && mem_preview != "") {
		eval(mem_preview);
    }
}

//}

//toggle_small_tabs
function toggle_small_tab(tab_id, num_tabs, p_id) {
    for(i=1;i<=num_tabs;i++){
		var elm = document.getElementById('small-tab'+i+'-'+p_id);
		var elmbody = document.getElementById('small-tab'+i+'-body-'+p_id);
		if(i != tab_id){
			elm.className='';
			elmbody.style.display = 'none';
		} else {
			elm.className='here';
			elmbody.style.display='block';
		}
    }
}

// tab selector function
function toggle_project_tab(tab_id, num_tabs, p_id) {
    for(i=1;i<=num_tabs;i++){
	var elm = document.getElementById('project-tab'+i+'-'+p_id);
	var elmbody = document.getElementById('project-tab'+i+'-body-'+p_id);
	if(i != tab_id){
	    elm.className='';
	    elmbody.style.display = 'none';
	} else {
	    elm.className='here';
	    elmbody.style.display='block';
	}
    }
    max_project_tab_body(tab_id, p_id);
    if (tab_id == 2 || tab_id == 3) {
	loopCheckboxes(p_id);
	// open publish to full height
	// scroll so that project header is at the top
	// open other tabs to full height

	// max_project_tab_body(tab_id, p_id);
    }
    // bulk upload form init
    if (tab_id == 4) {
	init_project_format_selector(p_id);
    }
}

// project publish tab selector function
function toggle_project_publish_tab(tab_id, num_tabs, p_id) {
    for(i=1;i<=num_tabs;i++){
		var elm = document.getElementById('project-publish-tab'+i+'-'+p_id);
		var elmbody = document.getElementById('project-publish-tab'+i+'-body-'+p_id);
		if(i != tab_id){
			elm.className='';
			elmbody.style.display = 'none';
		} else {
			elm.className='here';
			elmbody.style.display='block';
		}
    }
}

function toggle_ccit_tab(tab_id) {
    var num_of_tabs = 5; //This needs to reflect the number of tabs defined in the XSL in delivery.xsl
    for(i=1; i<=num_of_tabs; i++){
		var elm = document.getElementById('ccit-tab'+i);
		var elmbody = document.getElementById('ccit-tab'+i+'-body');
		if(i != tab_id){
			elm.className='';
			elmbody.style.display = 'none';
		} else {
			elm.className='here';
			elmbody.style.display='block';
		}
    }
}

function toggle_do_tab(tab_id, num_tabs) {
    for(i=1;i<=num_tabs;i++){
		var elm = document.getElementById('do-tab'+i);
		var elmbody = document.getElementById('do-tab'+i+'-body');
		if(i != tab_id){
			elm.className='';
			elmbody.style.display = 'none';
		} else {
			elm.className='here';
			elmbody.style.display='block';
		}
    }
}

function toggle_config_utils(div_id){
    $("#body-"+div_id).toggle();
    if ( $("#"+div_id+"-toggle-icon").attr("src") != "images/icon_plus_orange.gif"){
		$("#"+div_id+"-toggle-icon").attr("src", "images/icon_plus_orange.gif");
    } else {
		$("#"+div_id+"-toggle-icon").attr("src", "images/icon_minus_orange.gif");
    }
    if ((div_id == 'configure-utils' && floating) || (format_id == '1' && div_id == 'configure-utils')) {
		toggle_move_mode();
    }
}

function open_config_utils(div_id) {
    var elm = document.getElementById('body-'+div_id);
    if(elm.style.display == ''){
		toggle_config_utils(div_id);
    }
}

function close_config_utils(div_id) {
    var elm = document.getElementById('body-'+div_id);
    if(elm.style.display == 'block'){
		toggle_config_utils(div_id);
    }
}

// swap navigation and context help

function context_help() {
    var tdBody = document.getElementById('td-body');
    var helpBody = document.getElementById('context-help-content');
    var helpHeader = document.getElementById('help-header');
    var navHeader = document.getElementById('nav-header');
    var navButton = document.getElementById('show-hide-nav-img');
    var navCnt = document.getElementById('nav-container');
    navCnt.style.width = 175 + 'px';
    if(typeof(navButton) != 'undefinied' && navButton) {
		if(navButton.style.display == 'block'){
			toggle('show-hide-nav-img');
			navCnt.style.width = 12 + 'px';
		} else {
			toggle_single_div('navigation');
		}
    } else {
		toggle_single_div('navigation');
    }
    toggle_single_div('context-help', getRealHeight(tdBody));
    helpBody.style.height = getRealHeight(tdBody) - getRealHeight(helpHeader) - getRealHeight(navHeader) - 1 + 'px';
    if(domtype == 'safari'){
		helpBody.style.height = 512 + 'px';
    }
}

function show_nav_update() {
    var navCnt = document.getElementById('nav-container');
    var navButton = document.getElementById('show-hide-nav-img');
    navButton.style.display = 'none';
    navCnt.style.width = 175 + 'px';
}

function hide_nav_update() {
    var navCnt = document.getElementById('nav-container');
    var navButton = document.getElementById('show-hide-nav-img');
    navButton.style.display = 'block';
    if (domtype == 'safari'){
		navCnt.style.width = 12 + 'px';
    }
}

function show_hide_navigation() {
    var nav = document.getElementById('body-navigation');
    if(nav.style.display == '' || nav.style.display == 'none'){
		nav.style.display = 'block';
		open_div_x('body-navigation', 170);
		tz_tabs_nav_cookie.hide = 'false';
		tz_tabs_nav_cookie.store();
		show_nav_update();
    } else {
		close_div_x('body-navigation', 170);
		tz_tabs_nav_cookie.hide = 'true';
		tz_tabs_nav_cookie.store();
		hide_nav_update();
    }

    // position dfa upload layer
    if ($("#dfa-upload-layer").is("div")) {
		position_dfa_upload_layer();
    }
}

function show_hide_init(){
    var nav = document.getElementById('body-navigation');
    if (tz_tabs_nav_cookie.hide == 'true') {
    	hide_nav_update();
    } else {
	nav.style.display = 'block';
	show_nav_update();
    }
}

function hide_nav() {
    var nav = document.getElementById('body-navigation');
    close_div_x('body-navigation', 170);
    window.setTimeout("hide_nav_update()",500);
}

function show_nav() {
    var nav = document.getElementById('body-navigation');
    nav.style.display = 'block';
    open_div_x('body-navigation', 170);
    show_nav_update();
}

function close_s_panel() {
    var s_panel = document.getElementById('s_panel');
    s_panel.style.display = 'none';
    tabsVirginInput = document.getElementById('my-details-tabs-virgin');
    if (typeof(tabsVirginInput) && tabsVirginInput) {
		tabsVirginInput.checked = false;
    }

    values = "tabs_virgin=0";
    loadXMLDoc('mod_user_details.phtml', values);
}

function open_add_new_client() {
    var elm = document.getElementById('body-add-client');
    if(elm.style.display == ''){
		toggle_single_div('add-client');
    }
}

function open_add_new_project() {
    var elm = document.getElementById('body-add-project');
    if(elm.style.display == ''){
		toggle_single_div('add-project');
    }
}

function max_project_tab_body(me, p_id) {
    var elm = document.getElementById('project-tab' + me + '-body-'+p_id);
    var elm_parent_body = document.getElementById('body-' + p_id);
    var elm_header = document.getElementById(p_id);
    var elm_parent = document.getElementById('tab-body');
    var publish_div = document.getElementById('project-publish-tab-'+p_id);
    var creatives_list = document.getElementById('project-creatives-holder-'+p_id);
    var creatives_div = document.getElementById('publish-creatives-holder-'+p_id);
    var details_div = document.getElementById('publish-details-'+p_id);
    var new_top = getRealTop(elm_header) - getRealTop(elm_parent);
    //elm_parent_body.style.height = 471 + 'px';
    //elm.style.height = 443 + 'px';
    if(domtype == 'mozilla' || domtype == 'safari' || ie_variant == 7) {
		elm_parent.scrollTop = new_top;
		elm_parent_body.style.height = (getRealHeight(elm_parent) - 43) + 'px';
		elm.style.height = (getRealHeight(elm_parent_body) - 45) + 'px';
		if(typeof(publish_div) != 'undefined' && publish_div){
			publish_div.style.height = (getRealHeight(elm_parent_body) - 47) + 'px';
			details_div.style.height = (getRealHeight(elm_parent_body) - 181) + 'px';
			if(typeof(creatives_div) != 'undefined' && creatives_div){
			    creatives_div.style.height = 290 + 'px';
			    creatives_list.style.height = (getRealHeight(elm_parent_body) - 150) + 'px';
			}
		}
    }
    if(domtype == 'msie' && ie_variant == 6) {
		elm_parent.scrollTop = new_top;
		elm_parent_body.style.height = (getRealHeight(elm_parent) - 27) + 'px';
		elm.style.height = (getRealHeight(elm_parent_body) - 43) + 'px';
		if(typeof(publish_div) != 'undefined' && publish_div){
			publish_div.style.height = (getRealHeight(elm_parent_body) - 37) + 'px';
			details_div.style.height = (getRealHeight(elm_parent_body) - 186) + 'px';
			if(typeof(creatives_div) != 'undefined' && creatives_div){
			    creatives_div.style.height = 280 + 'px';
			    creatives_list.style.height = (getRealHeight(elm_parent_body) - 160) + 'px';
			}
		}
    }
}

function max_publish_delivery(p_id) {
    var elm_parent_body = document.getElementById('tab-body-5');
    var creatives_div = document.getElementById('publish-creatives-holder-'+p_id);
    var details_div = document.getElementById('publish-details-'+p_id);
    if(domtype == 'mozilla' || domtype == 'safari') {
	if(typeof(creatives_div) != 'undefined' && creatives_div){
	    /* creatives_div.style.height = 284 + 'px';
	       details_div.style.height = 311 + 'px'; */
	    }
    }
    if(domtype == 'msie') {
	if(typeof(creatives_div) != 'undefined' && creatives_div){
	    /* creatives_div.style.height = 265 + 'px';
	       if(ie_variant == 7){
	       creatives_div.style.height = 280 + 'px';
	       }
	       details_div.style.height = 302 + 'px'; */
	}
    }
}

function sort_list(obj_type, order_by, order, tab) {
    var new_url = tabs_http_base + obj_type + "/list.phtml?order_by=" + order_by + "&order=" + order;
    if (obj_type == 'project') {
		if (tab == '2') {
			new_url += "&archived=" + 'true';
		} else {
			new_url += "&archived=" + 'false';
		}
    } else {
		new_url += "&tab=" + tab;
    }
    document.location.href = new_url;
}

// Enabling and disabling functions for form elements - ripped from ZebraOne

function disable(ele){
    if (ele) {
		ele.disabled = true;
		ele.value = '';
		ele.style.backgroundColor = '#cccccc';
    }
}

function enable(ele, val){
    if (ele) {
		ele.disabled = false;
		if (typeof val != "undefined") {
			ele.value = val;
		} else {
			ele.value = '1';
		}
		ele.style.backgroundColor = '#ffffff';
    }
}

function disableradio(ele) {
    if (ele) {
		ele.disabled = true;
    }
}

function enableradio(ele) {
    if (ele) {
		ele.disabled = false;
    }
}

function disabletext(ele) {
    if (ele && ele.style) {
		ele.style.color = '#cccccc';
    }
}

function enabletext(ele) {
    if (ele && ele.style) {
		ele.style.color = '#000000';
    }
}


// INTERFACE SCRIPTS ENDS


// COOKIE FUNCTIONALITY
function Cookie(document, name, hours, path, domain, secure) {
    this.$document = document;
    this.$name = name;
    if (hours) {
		this.$expiration = new Date((new Date()).getTime() + hours*3600000);
    } else {
		this.$expiration = null;
    }
    if (path){
		this.$path = path;
    }
}

function _Cookie_store() {
    var cookieval = "";
    for(var prop in this) {
		if ((prop.charAt(0) == '$') || ((typeof this[prop]) == 'function')) {
			continue;
		};
		if (cookieval != "") {
			cookieval += '&';
		};
		cookieval += prop+':'+escape(this[prop]);
    };
    var cookie = this.$name +'='+cookieval;
    if (this.$expiration) {
		cookie+='; expires='+this.$expiration.toGMTString();
    };
    if (this.$path) {
		cookie+=';path='+this.$path;
    };
    this.$document.cookie = cookie;
}

function _Cookie_load() {
    var allcookies = this.$document.cookie;
    if (allcookies == "") {
		return false;
    };
    var start = allcookies.indexOf(this.$name + '=');
    if(start == -1) {
		return false;
    };
    start += this.$name.length + 1;
    var end = allcookies.indexOf(';', start);
    if(end == -1) {
		end = allcookies.length;
    };
    var cookieval = allcookies.substring(start, end);
    var a = cookieval.split('&');
    for(var i=0; i < a.length; i++) {
		a[i] = a[i].split(':');
    };
    for(var i = 0; i < a.length; i++) {
		this[a[i][0]] = unescape(a[i][1]);
    };
    return true;
}

new Cookie();
Cookie.prototype.store=_Cookie_store;
Cookie.prototype.load=_Cookie_load;

var tz_tabs_nav_cookie = new Cookie(document, "tz_tabs_nav_cookie", 1000,"/");
if (!tz_tabs_nav_cookie.load() || tz_tabs_nav_cookie.hide == null) {
    //tz_tabs_nav_cookie.hide = 'false';
 }
// COOKIE FUNCTIONALITY ENDS

var iframe_doc;
var iframe_window;
function tz_get_iframe_content(id) {
    var iframeDoc;
    iframeObj = document.getElementById(id);
    if (iframeObj.contentWindow) {
		iframe_window = iframeObj.contentWindow;
        // IE6, Mozilla, NS7, IE5.5 ...
        if (typeof(iframeObj.contentWindow.document)=='unknown') {
            iframeDoc = false;
        } else {
            iframeDoc = iframeObj.contentWindow.document;
        }
    } else if (iframeObj.contentDocument) {
        // Safari, Opera, NS6 ...
        iframeDoc = iframeObj.contentDocument;
    } else if (iframeObj.document) {
        // IE5 ...
        iframeDoc = iframeObj.document;
    } else {
        // ??
        iframeDoc = false;
    }
    return iframeDoc;
}

//new
function tz_get_iframe_content_doc(doc,id) {
    var iframeDoc;
    var iframeObj = doc.getElementById(id);
    if (iframeObj.contentWindow) {
		iframe_window = iframeObj.contentWindow;
        // IE6, Mozilla, NS7, IE5.5 ...
        if (typeof(iframeObj.contentWindow.document)=='unknown') {
            iframeDoc = false;
        } else {
            iframeDoc = iframeObj.contentWindow.document;
        }
    } else if (iframeObj.contentDocument) {
        // Safari, Opera, NS6 ...
        iframeDoc = iframeObj.contentDocument;
    } else if (iframeObj.document) {
        // IE5 ...
        iframeDoc = iframeObj.document;
    } else {
        // ??
        iframeDoc = false;
    }
    return iframeDoc;
}

//
var in_move_mode = false;
function refresh_config_iframe() {
    // clear out other iframe first
    var testiframe = document.getElementById('browseriframe_test');
    testiframe.src = "about:blank";

    //Need to check if we are previewing roadblock or creative level.
    //This is needed to get round the mispositioning of the creative bug when the browseriframe src is set while it is hidden.
    if (typeof(roadblock_iframe_src) != "undefined" && $("#roadblockiframe").css("display") == "block"){
		var roadblockiframe = document.getElementById('roadblockiframe');
		roadblockiframe.src = roadblock_iframe_src;
    }
    else{
		var myiframe = document.getElementById('browseriframe');
		myiframe.src = config_iframe_src + "&rnd=" + Math.random();
    }
    if (!in_move_mode) {
        setTimeout("init_move_mode()", 1000);
    }
}

function reset_preview_iframes() {
    var testiframe = document.getElementById('browseriframe_test');
    testiframe.src = "about:blank";
    var previewiframe = document.getElementById('browseriframe');
    previewiframe.src = "about:blank";

    var roadblockiframe = document.getElementById('roadblockiframe');
    if (typeof(roadblock_iframe_src) != "undefined"){
		roadblockiframe.src = "about:blank";
    }
}

function in_array(needle, haystack){
    for (i=0;i<haystack.length;i++){
		if(haystack[i]==needle){
			return i;
		}
    }
    return -1;
}

function change_setup_url(creative_id) {
    url_value = document.getElementById('config_url').value;
    config_iframe_src = tabs_http_base + 'creative/test_advert_main.phtml?config_mode=false&creative_id=' + creative_id + '&override_url=' + escape(url_value);
    preview_iframe_src = config_iframe_src;
    document.getElementById('test_url').value = url_value;
    values = "creative_id="+creative_id+"&url="+escape(url_value);
    loadXMLDoc('./creative/mod_preview_url.phtml', values);
    refresh_config_iframe();
}

function restore_default_url(creative_id) {
    var new_target = 'http://adpreview.tangozebra.com';
    config_iframe_src = tabs_http_base + 'creative/test_advert_main.phtml?config_mode=false&creative_id=' + creative_id + '&override_url=' + escape(new_target);
    preview_iframe_src = config_iframe_src;
    document.getElementById('config_url').value = new_target;
    //preview_iframe_src = new_target;
    document.getElementById('test_url').value = new_target;
    values = "creative_id="+creative_id+"&url="+escape(new_target);
    loadXMLDoc('./creative/mod_preview_url.phtml', values);
    refresh_config_iframe();
}

var showed_click_warning = false;
var click_int_warning = "";
function show_click_warning() {
    if (!showed_click_warning && click_int_warning != "" && typeof(click_int_warning) != 'undefined') {
		//tabs_error(click_int_warning);
		open_config_utils('click-int-panel');
		showed_click_warning = true;
    }
}

function tz_pos(o) {
    x = o.offsetLeft;
    y = o.offsetTop;
    p = o.offsetParent;
    while(p!=null) {
		x+=p.offsetLeft;
		y+=p.offsetTop;
		p=p.offsetParent;
    }
    return Array(x,y);
}

function tz_attach_event(ev,fn) {
    if(window.addEventListener) {
		window.addEventListener(ev, fn, false);
    } else if(window.attachEvent) {
		window.attachEvent("on"+ev,fn);
    }
}

function rectangle_overlap(x1,y1,w1,h1,x2,y2,w2,h2) {
    if((x2<=x1+w1) && (x2+w2>=x1) && (y2<=y1+h1) && (y2+h2>=y1)) {
		return true;
    } else {
		return false;
    }
}

function select_conflicts(select, target) {
    return rectangle_overlap(getRealLeft(select), getRealTop(select),
							 select.offsetWidth, select.offsetHeight,
							 getRealLeft(target), getRealTop(target),
							 target.offsetWidth, target.offsetHeight);
}

function hide_conflicting_elements(me) {
    var ns = document.getElementsByTagName('select');
    //    var ne = document.getElementsByTagName('embed');
    var no = document.getElementsByTagName('object');
    if (ns && typeof(ns)!="undefined") {
		for (var i=0; i<ns.length; i++) {
			if (select_conflicts(ns[i], me)) {
				ns[i].style.visibility = 'hidden';
			}
		}
    }

    if (no && typeof(no)!="undefined") {
		for (var i=0; i<no.length; i++) {
			// FIXME: IE DOESN'T SEE THE OBJECT IN PREVIEW AS A CONFLICT
			if (select_conflicts(no[i], me)) {
				no[i].style.visibility = 'hidden';
			}
		}
    }
    if((navigator.appName.indexOf("Netscape") != -1 || navigator.userAgent.indexOf("Mozilla/5") != -1) && navigator.userAgent.indexOf("Safari") ==-1) {
		if (typeof(ne)!="undefined" && ne) {
			for (var i=0; i<ne.length; i++) {
				if (select_conflicts(ne[i], me)) {
					ne[i].style.visibility = 'hidden';
				}
			}
		}
    }
}

function show_all_conflicts() {
    var ns = document.getElementsByTagName('select');
    var ne = document.getElementsByTagName('embed');
    var no = document.getElementsByTagName('object');
    if (ns && typeof(ns)!="undefined") {
		for (var i=0; i<ns.length; i++) {
			ns[i].style.visibility = '';
		}
    }
    if (no && typeof(no)!="undefined") {
		for (var i=0; i<no.length; i++) {
			no[i].style.visibility = '';
		}
    }
    if((navigator.appName.indexOf("Netscape") != -1 || navigator.userAgent.indexOf("Mozilla/5") != -1) && navigator.userAgent.indexOf("Safari") ==-1) {
		if (ne && typeof(ne)!="undefined") {
			for (var i=0; i<ne.length; i++) {
				ne[i].style.display = '';
			}
		}
    }
}

// test maximize minimize function
function min_max(me, Ydiff) {
    var elm = document.getElementById(me);
    var e = document.getElementById("tab-body");
    if (typeof(e) != 'undefined' && e) {
		var eH = getRealHeight(e);
		Ydiff = parseInt(Ydiff) + eH;
    }
    if (parseInt(navigator.appVersion)>3) {
		if (navigator.appName=="Netscape") {
			winW = window.innerWidth;
			winH = window.innerHeight;
			elm.style.height = winH - Ydiff;
			elm.style.width = winW - 300;
		}
		if (navigator.appName.indexOf("Microsoft")!=-1) {
			winW = document.body.offsetWidth;
			winH = document.body.offsetHeight;
			elm.style.height = winH - Ydiff;
			//elm.style.width = winW - 300;
		}
    }
}

function trim(strText){
    while (strText.substring(0,1) == ' '){
        strText = strText.substring(1, strText.length);
	}
    while (strText.substring(strText.length-1,strText.length) == ' '){
        strText = strText.substring(0, strText.length-1);
	}
	return strText;
}


// edit my details
function update_my_details() {
    for(var i=1;i<11;i++){
		var dis = document.getElementById('display-'+i);
		var edt = document.getElementById('edit-'+i);
		if(typeof(dis) != 'undefined' && dis){
			dis.style.display='none';
		}
		if(typeof(edt) != 'undefined' && edt){
			edt.style.display='block';
		}
    }
}

// Send preview - logo preview
function logo_preview(pid){
    var limg = document.getElementById('logo-image-'+pid);
    var lprw = document.getElementById('logo-preview-'+pid);
    //limg.style.left = getRealLeft(lprw)+'px';
    //limg.style.top = getRealTop(lprw)+'px';
    limg.style.display='block';

}

function show_loading_indicator(){
    var shell = document.getElementById('tabs-shell');
    var shadowpng = document.getElementById('tabs-shadowpng');
    var loading = document.getElementById('tabs-loading');
    shell.style.display = 'none';
    shadowpng.style.display ='none';
    loading.style.display = 'block';
}

function filename_is_clean(strFilename) {
	strFilename = trim(strFilename);
	var illegalChars="'#[]{}=)+*(&%$:;£\"!^¬`,|?~>< ";
	for (i=0;i<strFilename.length;i++){
		if(illegalChars.indexOf(strFilename.charAt(i))!=-1){
			return false;
		}
	}

	file_bits = strFilename.split(".");
	if (file_bits.length >2) { 
		return false;
	}

	if (file_bits[file_bits.length-1]=="SWF") { //no capital extensions for motifation
		return false;
	}

	return true;
}

function loopCheckboxes(project_id){
	var checkedBoxes = false;

	$("#publish-creatives-holder-"+project_id+" input[@type='checkbox']").each(function(i){
																				   if(this.checked == true) { checkedBoxes = true; };
																			   });

	if(checkedBoxes){
		activatePublishButton();
	} else {
		disablePublishButton();
	}
}

function activatePublishButton(){
    var publishButtonId = "project-publish-tab2-link-"+ project_id;
    if(document.getElementById(publishButtonId) != 'undefined' && document.getElementById(publishButtonId)) {
		document.getElementById(publishButtonId).href='javascript:toggle_project_publish_tab(2, 2, '+project_id+');';
		document.getElementById(publishButtonId).className='';
    }
}

function disablePublishButton(){
    var publishButtonId = "project-publish-tab2-link-"+ project_id;
    if(document.getElementById(publishButtonId) != 'undefined' && document.getElementById(publishButtonId)) {
		document.getElementById(publishButtonId).href='javascript:void(0);';
		document.getElementById(publishButtonId).className='disabled-button-dc';
    }
}

function checkboxes_select_all(table_id, button_id) {
    $("#"+table_id+" input[@type='checkbox']").each(function(i){
        if(this.disabled != true){
            this.checked = true;
        }
    });
    $("#"+button_id+"-all").toggle();
    $("#"+button_id+"-none").toggle();
}

function checkboxes_deselect_all(table_id, button_id) {
    $("#"+table_id+" input[@type='checkbox']").each(function(i){
        if(this.disabled != true){
            this.checked = false;
        }
    });
    $("#"+button_id+"-none").toggle();
    $("#"+button_id+"-all").toggle();
}
