function displayWatchPage(model) {
	var state = window.state;
	var oldUserId = state.userId;

	if (state == null) {
		state = new Object();
		window.state = state;

		state.userId = model.userId;
		state.guest = model.guest;
	}

	displayHeader(model);

	var flashVars= {
		"widgetId" : 1585679,
		"userId": model.userId,
		"widgetAutoplay": false,
		"displayFooter": true
	};

	displayWidget('widget-embed','widget-parent', 400, 500, flashVars);
	setClassName('widget-parent', 'watch-embed');
}

function displaySplashPage(model) {
	var state = window.state;
	var oldUserId = state.userId;

	if (state == null) {
		state = new Object();
		window.state = state;

		state.userId = model.userId;
		state.guest = model.guest;
	}

	displayHeader(model);
}

function displayWidgetGallery(model){
	var state = window.state;
	if (state == null) {
		state = new Object();
		window.state = state;
	}

	state.model = model;
	displayHeader(model);
	updateBrowseLinks();

	hideIf('no-widgets', (model.widgets.length > 0));


	if(model.widget != null){
		var displayHelper = getWidgetDisplayHelper(model.widget);
		displayWidgetPreview(model.widget.id, displayHelper.displayWidth, displayHelper.displayHeight, displayHelper.width, displayHelper.borderWidth, displayHelper.borderHeight, displayHelper.borderType , displayHelper.autoplay, displayHelper.displayFooter);
	}

	var widgetMap = new Object();

	for(var widgetIdx = 0; widgetIdx < model.widgets.length; widgetIdx++){
		var widget = model.widgets[widgetIdx];

		for(var categoryIdx = 0; categoryIdx < widget.categories.length; categoryIdx++){
			var category = widget.categories[categoryIdx];
			if(widgetMap[category] == null){
				widgetMap[category] = new Array();
			}
			widgetMap[category].push(widget);
		}
	}

	model.widgetMap = widgetMap;
	state.model = model;

	for(category  in widgetCategories){
		var categoryId = widgetCategories[category];

		setClassName(categoryId+'-category', (widgetMap[category] != null) ? 'gallery-category-collapsed' : 'hide')

		if(widgetMap[category] != null){
			var widgetCategoryAry = widgetMap[category];
			setTextContent(categoryId+'-category-num-widgets', widgetCategoryAry.length + ((widgetCategoryAry.length > 1) ? ' Widgets' : ' Widget'))
			prepareRepeatedNodes(categoryId+'-widget-0', widgetCategoryAry.length );

			for(var widgetIdx = 0; widgetIdx < widgetCategoryAry.length; widgetIdx++){
				var widget = widgetCategoryAry[widgetIdx];
				byId(categoryId+'-widget-image-'+widgetIdx).src = (widget.imageId != null) ? 'media.html?id=' + widget.imageId : '../images/default-channel-icon.jpg';
				setTextContent(categoryId+'-widget-name-'+widgetIdx, widget.title);

				var displayHelper = getWidgetDisplayHelper(widget);

				byId(categoryId+'-widget-'+widgetIdx).onclick = new Function('displayWidgetPreview('+widget.id+', '+displayHelper.displayWidth+', '+displayHelper.displayHeight+', '+displayHelper.width+', '+displayHelper.borderWidth+', '+displayHelper.borderHeight +', \''+displayHelper.borderType+'\',   '+displayHelper.autoplay+', '+displayHelper.displayFooter+', \''+jsEscape(widget.title)+'\' );');

			}
		}
	}
}

function getWidgetDisplayHelper(widget){
	var displayHelper = new Object();

	displayHelper.width = (widget.width != null) ? widget.width : 360;
	displayHelper.displayHeight = (widget.width != null) ? getFullPlayerHeight(widget.width, widget.border) : 260;
	displayHelper.displayWidth = (widget.width!= null) ? getFullPlayerWidth(widget.width, widget.border) : 360;
	if(displayHelper.width > 400){ //has to fit in right hand column
		var scale = 400 / displayHelper.width;
		displayHelper.displayHeight  *= scale;
		displayHelper.displayWidth  *= scale;
	}

	displayHelper.borderHeight = (widget.border != null) ? widget.border.height : null;
	displayHelper.borderWidth  = (widget.border != null) ? widget.border.width : null;
	displayHelper.borderType = (widget.border != null) ? widget.border.type : null;
	displayHelper.displayFooter = (widget.border != null &&  (widget.border.type == 'Ad' || widget.border.type == 'Gordo'));
	displayHelper.autoplay = widget.autoplay;
	return displayHelper;
}

function formatCategoryName(name){
	if(name != null){
		name = name.toLowerCase();
		return name.replace(/\s*&\s*/g, '-and-');
	}else{
		return null;
	}
}


function displayProfileAdminModel(model){
	var state = window.state;
	if (state == null) {
		state = new Object();
		window.state = state;
	}

	state.model = model;
	displayHeader(model);

	byId('view-profile-image').src = (model.imageUrl != null) ? model.imageUrl : "../images/guest.gif";
	setTextContent('view-profile-username', model.username);
	setTextContent('view-profile-cozmojo', model.cozmojo.toFixed(0));
	setTextContent('view-profile-confidence', model.confidence.toFixed(1) + '%');
	setTextContent('view-profile-total-viewed-videos', model.totalViewedVideos);
	setTextContent('view-profile-total-rated-videos', model.totalRatedVideos);
	setTextContent('view-profile-total-favorited-videos', model.totalFavoriteWidgets);

	prepareRepeatedNodes('owned-widget-0', model.widgets.length);
	for(var widgetIdx = 0; widgetIdx < model.widgets.length; widgetIdx++){
		setTextContent('owned-widget-name-'+widgetIdx, model.widgets[widgetIdx].title);
		byId('owned-widget-name-'+widgetIdx).href = 'manage-widgets2.html?widgetId='+model.widgets[widgetIdx].id;
	}
	hideIf('no-widgets', model.widgets.length > 0);

	prepareRepeatedNodes('owned-network-0',model.networks.length);
	for(var networkIdx = 0; networkIdx < model.networks.length; networkIdx++){
		setTextContent('owned-network-name-'+networkIdx, model.networks[networkIdx].name);
		byId('owned-network-name-'+networkIdx).href = 'manage-networks.html?networkId='+model.networks[networkIdx].id;
	}
	hideIf('no-networks', model.networks.length > 0);

	//todo
	prepareRepeatedNodes('owned-campaign-0', 0);
	hideIf('no-campaigns', false);

	setClassName('profile-action-div', 'view-mode');

	//Account Info
	setTextContent('manage-profile-username-span', model.username);
	if(model.email!= null) byId('manage-profile-email').value=model.email;
	byId('manage-profile-accountType-affiliate').checked = false;
	byId('manage-profile-accountType-producer').checked = false;
	byId('manage-profile-accountType-advertiser').checked = false;
	if(model.accountTypes != null){
		for(var acctIdx = 0; acctIdx < model.accountTypes.length; acctIdx++){
			byId('manage-profile-accountType-'+model.accountTypes[acctIdx].toLowerCase()).checked = true;
		}
	}
	if(model.gender!= null) setSelectValue('manage-profile-gender-sel', model.gender);
	if(model.birthDay!= null) setSelectValue('manage-profile-birthDay', model.birthDay);
	if(model.birthMonth!= null) setSelectValue('manage-profile-birthMonth', model.birthMonth);
	if(model.birthYear!= null) setSelectValue('manage-profile-birthYear', model.birthYear);
	byId('manage-profile-image').src = (model.imageUrl != null) ? model.imageUrl :(model.gender == 'Male' ? "../images/guy2.gif" : "../images/girl2.gif");

	//Contact Info
	if(model.city!= null) byId('manage-profile-address1').value= model.address1;
	if(model.city!= null) byId('manage-profile-address2').value= model.address2;
	if(model.city!= null) byId('manage-profile-city').value= model.city;
	if(model.country != null) setSelectValue('manage-profile-state-sel', model.state);
	if(model.country != null) setSelectValue('manage-profile-country-sel', model.country);
	if(model.zipcode!= null) byId('manage-profile-zipcode').value = model.zipcode;
	if(model.zipcode!= null) byId('manage-profile-phone').value = model.phone;
}

function displayImportVideoModel(model){
	var state = window.state;
	if (state == null) {
		state = new Object();
		window.state = state;
	}

	state.model = model;
	displayHeader(model);

	var ownedChannels = model.ownedChannels;
	var channelManagerSelect = byId('import-channel-id');
	channelManagerSelect.options.length=0;
	for(var count = 0; count < model.ownedChannels.length; count++){
		var channel = model.ownedChannels[count];
		addOption(channelManagerSelect, channel.name, channel.id);
	}

	byId('import-video-url').value = '';
	byId('tag-input').value = '';
	byId('username-input').value = '';
}

function displayChannelDescriptionModel(model){
	var state = window.state;
	if (state == null) {
		state = new Object();
		window.state = state;
	}

	state.model = model;

	setClassName('edit-channel-description-form', (model.administratorAccess) ? 'admin-access' : null);
	setClassName('publish-channel-form', (model.administratorAccess) ? 'admin-access' : null);

	var contentProviderSelect = byId('edit-channel-content-provider');
	contentProviderSelect.options.length=0;
	addOption(contentProviderSelect, 'Unspecified', 'none');

	for(var count = 0; count < model.contentProviders.length; count++){
		var contentProvider = model.contentProviders[count];
		addOption(contentProviderSelect, contentProvider, contentProvider);
	}

	if(model.channel != null) {
		var channel = model.channel;
		byId('edit-channel-form-name').value = channel.name;
		byId('edit-channel-form-description').value = (channel.description != null) ? channel.description : '';

		byId('edit-channel-description-channelId').value = channel.id;
		byId('edit-channel-import-channelId').value = channel.id;
		byId('edit-channel-source-channelId').value = channel.id;
		byId('publish-channel-channelId').value = channel.id;
		setTextContent('channel-manager-display-channelId', channel.id);

		byId('edit-channel-form-url').value = (channel.url != null) ?  channel.url : '';
		byId('edit-channel-form-image').value = null;
		byId('edit-channel-form-image-preview').src = (channel.imageUrl != null) ? channel.imageUrl : '../images/ch-img.gif';
		byId('edit-channel-form-tags').value = (channel.tags != null) ? channel.tags.toString() : '';

		updateCheckboxes('edit-channel-form-category-', channel.categories);

		var allAges = (channel.minAge == 0 && channel.maxAge == 100);

		byId('edit-channel-age-min').value = (!allAges) ? channel.minAge : '';
		byId('edit-channel-age-max').value = (!allAges) ? channel.maxAge : '';
		byId('edit-channel-all-ages').checked = allAges;
		byId('edit-channel-age-min').disabled = allAges;
		byId('edit-channel-age-max').disabled = allAges;

		setSelect('edit-channel-form-language', channel.language);
		setSelect('edit-channel-content-provider', (channel.contentProvider != null) ? channel.contentProvider : 'none');

		if(!isNewChannel){
			var ownedChannels = model.ownedChannels;
			var channelManagerSelect = byId('channel-manager-select-channelId');
			channelManagerSelect.options.length=0;
			for(var count = 0; count < model.ownedChannels.length; count++){
				var ownedChannel = model.ownedChannels[count];
				addOption(channelManagerSelect, ownedChannel.name, ownedChannel.id);
			}
		}

		var channelTitle = ((model.channel != null && model.channel.id != null) || isNewChannel) ?  model.channel.name : '< NONE SELECTED >';
		byId('channel-preview-title').innerHTML = htmlEscape(channelTitle );
		refreshChannelPreview();
	}
}

function displayChannelSourceModel(model){
	var state = window.state;
	if (state == null) {
		state = new Object();
		window.state = state;
	}

	state.model = model;
	var isChannel = (model.channel != null && model.channel.id != null);
	var hasFeeds = isChannel && (model.type == 'Feed');
	var hasLineup = isChannel && !hasFeeds;

	setClassName('channel-source-div', (hasFeeds) ? 'feed-source' : (isChannel ? 'user-source' : 'no-source'));
	showIf('feed-warning', (hasFeeds && !isNewChannel));

	byId('edit-channel-type').disabled = isChannel;
	var adminMode = (isNewChannel) ? 'create-mode' : 'edit-mode';
	setButtonMode(adminMode, 3);

	var feedLocations = model.feedLocations;
	var feedLocationValue = '';
	if ((feedLocations != null) && (feedLocations.length > 0) && (feedLocations[0] != null)) {
		feedLocationValue = feedLocations[0];
	}
	var feedOrder = (model.feedOrder == null) ? 0 : model.feedOrder;

	byId('edit-channel-type').value = (model.type != null) ? model.type : 'User';
	setSelect('edit-channel-shuffle', (model.channel.shuffle) ? 'true' : 'false');
	byId('edit-channel-feed-location').value = feedLocationValue;
	byId('edit-channel-feed-order').value = feedOrder;

	setSelect('import-video-order-select', 'end')
	resetInputs('import-video-url-');
	resetInputs('import-video-username-');
	resetInputs('import-video-tag-');

	if(!hasFeeds) {
		displayChannelLineup();
	}
}


function displayChannelAdminModel(model){
	var state = window.state;
	if (state == null) {
		state = new Object();
		window.state = state;
	}

	state.model = model;
	displayHeader(model);

	var ownedChannels = model.ownedChannels;
	var channelManagerSelect = byId('channel-manager-select-channelId');
	channelManagerSelect.options.length=0;
	for(var count = 0; count < model.ownedChannels.length; count++){
		var channel = model.ownedChannels[count];
		addOption(channelManagerSelect, channel.name, channel.id);
	}

	var ownedWidgets = model.ownedChannels;
	var widgetSelect = byId('channel-manager-select-widget');
	widgetSelect.options.length=0;
	for(var count = 0; count < model.ownedWidgets.length; count++){
		var widget = model.ownedWidgets[count];
		addOption(widgetSelect, widget.title, widget.id);
	}

	byId('channel-manager-allow-resyndication').checked = (model.channel != null  && model.channel.allowResyndication);



	displayChannelSourceModel(model);
	displayChannelDescriptionModel(model);
}

function displayChannelLineup(model) {
	var state = window.state;

    if(model != null){
	    if(state.model.channelId == model.channelId){
			model.listingShowIds = state.model.listingShowIds;
		}
		state.model = model;
    }else{
        model = state.model;
    }

	displayActiveTab('video-selection-tab-', 2, model.tabIndex);

	prepareRepeatedNodes('video-selection-div-0',model.tabVideos.length);

	for (var count = 0; count < model.tabVideos.length; count++) {
		var video = model.tabVideos[count];

		var checkbox = byId('video-selection-lineup-checkbox-'+count);
		var orderInput = byId('video-selection-lineup-number-input-'+count);

		if(aryContains(model.listingShowIds, video.id)){
			checkbox.checked = true;
			orderInput.value = aryFind(model.listingShowIds, video.id) + 1;
		}else{
			checkbox.checked = false;
			orderInput.value = '';
		}

		checkbox.onclick = new Function('toggleVideo('+video.id+', \''+orderInput.id+'\');');
		orderInput.onchange= new Function ('changeLineupOrder('+video.id+', \''+orderInput.id+'\');');

		replaceImage('video-selection-thumb-' + count, video.imageUrl);
		setTextContent('video-selection-title-' + count, video.title);
		setTextContent('video-selection-duration-'+count, getDurationString(video.duration));

		var hasMore = (video.detailedDescription != null && video.detailedDescription.length > video.description.length);
		setTextContent('video-selection-short-description-text-'+count, video.description);
		setTextContent('video-selection-detailed-description-text-'+count, video.detailedDescription);
		setClassName('video-selection-description-div-'+count,'show-short-description');
		showIf('video-selection-more-href-'+count, hasMore);
		byId('video-selection-more-href-'+count).href = 'javascript:setClassName(\'video-selection-description-div-'+count+'\',\'show-detailed-description\')';
		byId('video-selection-less-href-'+count).href = 'javascript:setClassName(\'video-selection-description-div-'+count+'\',\'show-short-description\')';

		setTextContent('video-selection-source-'+count, video.source);
		byId('video-selection-source-'+count).href = video.source;

		prepareChildList('video-selection-tags-'+count, video.tags.length, 'video-selection-tag-'+count+'-0', 'a' );

		for(var tagIdx = 0; tagIdx < video.tags.length; tagIdx++){
			setTextContent('video-selection-tag-'+count+'-'+tagIdx, video.tags[tagIdx]);
			byId('video-selection-tag-'+count+'-'+tagIdx).href ='javascript:gotoVideoSearch(\''+jsEscape(video.tags[tagIdx])+'\');';
			if(tagIdx <  video.tags.length-1){
				insertTextAfter('video-selection-tag-'+count+'-'+tagIdx, ', ');
			}
		}

		prepareChildList('video-selection-channels-'+count, video.channelNames.length, 'video-selection-channel-'+count+'-0', 'a' );

		for(var channelIdx = 0; channelIdx < video.channelNames.length; channelIdx++){
			setTextContent('video-selection-channel-'+count+'-'+channelIdx, jsEscape(video.channelNames[channelIdx]));
			byId('video-selection-channel-'+count+'-'+channelIdx).href ='javascript:void(1);';
			if(channelIdx <  video.channelNames.length-1){
				insertTextAfter('video-selection-channel-'+count+'-'+channelIdx, ', ');
			}
		}

		byId('video-selection-favorite-href-'+count).href ='javascript:saveShow('+ video.id +', '+ !video.isFavorite +');';
		setTextContent('video-selection-favorite-href-'+count, (video.isFavorite) ? 'Remove from Favorites' : 'Add to Favorites');

		byId('video-selection-related-href-'+count).href ='javascript:gotoVideoSearch(\''+jsEscape(video.title)+'\');';

		var identifier = (video.owner == 'blip') ? video.additionalIdentifier : video.identifier;
		if(identifier != null){
			byId('video-selection-preview-href-'+count).href ='javascript:openPreviewVideoDialog(\''+jsEscape(video.owner)+'\', \''+ jsEscape(identifier) + '\');';
			byId('video-selection-title-'+count).href ='javascript:openPreviewVideoDialog(\''+jsEscape(video.owner)+'\', \''+ jsEscape(identifier) + '\');';
		}else{
			byId('video-selection-preview-href-'+count).href ='javascript:void(1);';
			byId('video-selection-title-'+count).href ='javascript:void(1);';
		}

	}

	displayPage('video-upper-selection-page', model.tabPage, 10, model.totalTabVideos, gotoAdminVideosPage);
	displayPage('video-lower-selection-page', model.tabPage, 10, model.totalTabVideos, gotoAdminVideosPage);
}

function displayWidgetDescriptionModel(model){
	var state = window.state;
	if (state == null) {
		state = new Object();
		window.state = state;
	}
	state.model = model;

	setClassName('edit-widget-description-form', (model.administratorAccess) ? 'admin-access' : null);
	setClassName('edit-widget-design-form', (model.administratorAccess) ? 'admin-access' : null);

	byId('edit-widget-description-widgetId').value = model.widgetId;
	byId('edit-widget-design-widgetId').value = model.widgetId;
	byId('edit-widget-source-widgetId').value = model.widgetId;
	byId('edit-widget-import-widgetId').value = model.widgetId;
	byId('publish-widget-widgetId').value = model.widgetId;

	byId('widget-title-text').value = (model.title == null) ? '' : model.title;
	var widgetTitle = (model.widgetId != null || isNewWidget) ? model.title : '< NONE SELECTED >';
	byId('widget-preview-title').innerHTML = htmlEscape(widgetTitle);
	refreshWidgetPreview();

	resetFileInput('widget-image');
	byId('widget-image-preview').src = (model.imageUrl != null) ? model.imageUrl : '../images/ch-img.gif';
	byId('widget-description').value = (model.description == null) ? '' : model.description;
//	setSelectValue('widget-category', (model.tags != null && model.tags[0] != null) ? model.tags[0] : 'Entertainment');
	byId('widget-url').value = (model.url != null) ? model.url : '';

	updateCheckboxes('widget-category-', model.categories);

	byId('widget-tags').value = (model.tags != null) ? model.tags.toString() : '';

	var allAges = (model.minAge == 0 && model.maxAge == 100);

	byId('widget-age-min').value = (!allAges) ? model.minAge : '';
	byId('widget-age-max').value = (!allAges) ? model.maxAge : '';
	byId('widget-all-ages').checked = allAges;
	byId('widget-age-min').disabled = allAges;
	byId('widget-age-max').disabled = allAges;

	setSelectValue('widget-language-select', model.language);

	setSelectValue('widget-admin-buttons', model.adminButtons);
	setSelectValue('widget-featured', ''+model.featured);
	setSelectValue('widget-display-video', model.displayVideo);
	setSelectValue('widget-display-only-user-related-widgets', model.displayOnlyUserRelatedWidgets);

	if(!isNewWidget){
		var widgetManagerSelect = byId('widget-manager-select');
		widgetManagerSelect.options.length = 0;
		for (var count = 0; count < model.ownedWidgets.length; count++) {
			var ownedWidget = model.ownedWidgets[count];
			addOption(widgetManagerSelect, ownedWidget.title, ownedWidget.id, (ownedWidget.id == model.widgetId));
		}
	}
}

function displayWidgetDesignModel(model){
	var state = window.state;
	if (state == null) {
		state = new Object();
		window.state = state;
	}
	state.model = model;

	var hasEmbed = (model.queryIds != null && model.queryIds.length > 0);

	setRadioValue('widget-skin-type-', (model.widgetBorder != null) ? model.widgetBorder.type : 'Gordo_Old')
	resetFileInput('widget-skin-input');
	resetFileInput('widget-ad-canvas-input');

	byId('widget-content-width').value =  (model.width != null) ? model.width : 360;
	byId('widget-border-width-input').value =  (model.widgetBorder != null) ? Math.round(getFullPlayerWidth(model.width, model.widgetBorder)) : 400;
	setTextContent('widget-border-height', (model.widgetBorder != null) ? Math.round(getFullPlayerHeight(model.width, model.widgetBorder)) : 500) ;
	setTextContent('skin-dimensions-width', (model.widgetBorder != null) ? model.widgetBorder.width / 2 : 400 );
	setTextContent('skin-dimensions-height', (model.widgetBorder != null) ? model.widgetBorder.height / 2 : 500 );

	byId('widget-manager-color-0').value = (model.themeColor1 != null ) ? model.themeColor1 : '0x000000' ;
	byId('widget-manager-color-1').value = (model.themeColor2 != null ) ? model.themeColor2 : '0x2D2D2D' ;
	byId('widget-manager-color-2').value = (model.fontColor1 != null ) ? model.fontColor1 : '0xFFFFFF' ;
	byId('widget-manager-color-3').value = (model.fontColor2 != null ) ? model.fontColor2 : '0x666666' ;
	byId('widget-manager-color-4').value = (model.footerColor != null ) ? model.footerColor : '0x000000' ;
	byId('widget-manager-color-5').value = (model.footerFontColor != null ) ? model.footerFontColor : '0xFFFFFF' ;
	updateColorPreviews();

	setRadioValue('widget-player-type-', (model.externalPlayer != null) ? model.externalPlayer.type : 'Cozmo')

	var isBrightcove = (model.externalPlayer != null &&  model.externalPlayer.type == 'Brightcove');
	showIf('brightcove-form', isBrightcove , 'upload-section')
	byId('brightcove-publisher-id').value = (isBrightcove) ? model.externalPlayer.publisherId : '';
	byId('brightcove-player-id').value = (isBrightcove) ?  model.externalPlayer.playerId : '';
	byId('brightcove-player-width').value = (isBrightcove) ?  model.externalPlayer.width : '';
	byId('brightcove-player-height').value = (isBrightcove) ?  model.externalPlayer.height : '';
	byId('brightcove-player-x').value = (isBrightcove) ?  model.externalPlayer.x : '';
	byId('brightcove-player-y').value = (isBrightcove) ?  model.externalPlayer.y : '';

	var isOtherExternalPlayer = (model.externalPlayer != null &&  model.externalPlayer.type == 'Other');
	showIf('external-player-form', isOtherExternalPlayer, 'upload-section')
	byId('external-player-url').value = (isOtherExternalPlayer) ?  model.externalPlayer.url : '';
	byId('external-player-width').value = (isOtherExternalPlayer) ?  model.externalPlayer.width : '';
	byId('external-player-height').value = (isOtherExternalPlayer) ?  model.externalPlayer.height : '';
	byId('external-player-x').value = (isOtherExternalPlayer) ?  model.externalPlayer.x : '';
	byId('external-player-y').value = (isOtherExternalPlayer) ?  model.externalPlayer.y : '';
	resetInputs('external-player-parameter-');
	if(isOtherExternalPlayer && model.externalPlayer.parameters != null){
		for(var paramIdx = 0; paramIdx < model.externalPlayer.parameters.length; paramIdx++){
			var paramAry = model.externalPlayer.parameters[paramIdx].split('=',2);
			if(paramIdx > 0) addInput('external-player-parameter-', paramIdx);
			byId('external-player-parameter-name-'+paramIdx).value = paramAry[0];
			byId('external-player-parameter-value-'+paramIdx).value = paramAry[1];
		}
	}

	showIf('external-add-videos-section', model.externalPlayer != null);
	showIf('cozmo-add-videos-section', model.externalPlayer == null);

	if(model.autoplay && model.initialScreen == 'channelSelection') {
		setSelectValue('widget-load-sequence', 'channelSelection');
	}else if(model.autoplay && model.initialScreen == 'showSelection') {
		setSelectValue('widget-load-sequence', 'showSelection');
	}else if(model.autoplay && !model.skipVideoScreen){
		setSelectValue('widget-load-sequence', 'autoplay');
	}else{
		setSelectValue('widget-load-sequence', 'intro');
	}

	resetFileInput('widget-intro-file');

	gotoCustomizeWidgetTab(0);

	var border = model.widgetBorder;

	flashvars= {
		"widgetId": model.widgetId,
		"contextId": model.contextId,
		"widgetAutoplay": model.autoplay
	};

	byId('widget-embed-code').value = (border != null ) ? getWidgetEmbed(model.width, flashvars, border.width, border.height, border.type) : getWidgetEmbed(model.width, flashvars);
	byId('widget-embed-code').disabled = (!hasEmbed);

	var displayWidth = Math.round(getFullPlayerWidth(border, model.width));
	var displayHeight = Math.round(getFullPlayerHeight(border, model.width));

	/*var clearspringConf= {
			"userId": "46ee90e0e59434e3",
			"widgetName": "Cozmo OnPage",
			"source": "widget-embed-code",
			"menuWidth": 400,
			"menuHeight": 210,
			"customCSS": "http://cdn.clearspring.com/launchpad/skins/grey.css",
			"targetElement" : "clearspring-menu",
			"widgetWidth" : displayWidth,
			"widgetHeight" : displayHeight,	
			"excludeTracking" : true
	};

	$Launchpad.ShowMenu(clearspringConf);*/

	byId('widget-allow-promotion').checked = model.allowPromotion;

	var demoUrl = 'http://www.cozmo.tv/main/demo.html?widgetId='+model.widgetId;
	byId('widget-demo-url').href = demoUrl;
}

function displayWidgetModel(model) {
	var state = window.state;
	if (state == null) {
		state = new Object();
		window.state = state;
	}

	state.model = model;
	displayHeader(model);

	//WIDGET SELECTION
	var widgetManagerSelect = byId('widget-manager-select');
	widgetManagerSelect.options.length = 0;
	for (var count = 0; count < model.ownedWidgets.length; count++) {
		var ownedWidget = model.ownedWidgets[count];
		addOption(widgetManagerSelect, ownedWidget.title, ownedWidget.id, (ownedWidget.id == model.id));
	}

	displayWidgetDescriptionModel(model);
	displayWidgetDesignModel(model);

	//Widget Source
	var hasWidget = model.widgetId != null;

	resetInputs('import-video-url-');
	resetInputs('import-video-feed-');
	displayWidgetQueries();

	hideIf('edit-widget-lineup', true);

	var adminMode = (hasWidget) ? 'edit-mode' : 'create-mode'
	setButtonMode(adminMode, 4);
}

function displayNetworkAdminModel(model){
	var state = window.state;
	if (state == null) {
		state = new Object();
		window.state = state;
	}

	state.model = model;
	displayHeader(model);

	//NETWORK SELECTION
	var networkManagerSelect = byId('network-manager-select');
	networkManagerSelect.options.length = 0;
	for (var count = 0; count < model.ownedNetworks.length; count++) {
		var ownedNetwork = model.ownedNetworks[count];
		addOption(networkManagerSelect, ownedNetwork.name, ownedNetwork.id, (ownedNetwork.id == model.id));
	}

	displayNetworkDescriptionModel(model);
	displayNetworkDesignModel(model);
	displayNetworkTargetModel(model);
	displayNetworkInstallModel(model);
}

function displayNetworkDescriptionModel(model){
	var state = window.state;
	if (state == null) {
		state = new Object();
		window.state = state;
	}
	state.model = model;

	byId('edit-network-description-networkId').value = model.networkId;
	byId('edit-network-design-networkId').value = model.networkId;
	byId('edit-network-target-networkId').value = model.networkId;
	byId('install-network-networkId').value = model.networkId;

	byId('network-name-text').value = (model.name == null) ? '' : model.name;
	var networkName = (model.networkId != null || isNewNetwork) ? model.name : '< NONE SELECTED >';
	byId('network-preview-title').innerHTML = htmlEscape(networkName);

	resetFileInput('network-image');
	byId('network-image-preview').src = (model.imageUrl != null) ? model.imageUrl : '../images/ch-img.gif';

	byId('network-description').value = (model.description == null) ? '' : model.description;

	var allAges = (model.minAge == 0 && model.maxAge == 100);

	byId('network-age-min').value = (!allAges) ? model.minAge : '';
	byId('network-age-max').value = (!allAges) ? model.maxAge : '';
	byId('network-all-ages').checked = allAges;
	byId('network-age-min').disabled = allAges;
	byId('network-age-max').disabled = allAges;

	model.networkWidgetsPage = 0;
	model.totalNetworkWidgets = (model.approvedWidgets != null) ? model.approvedWidgets.length : 0;

	state.model = model;

	displayNetworkWidgets();
	
	resetInputs('network-url-');
	if( model.urls != null){
		for(var urlCount = 0; urlCount < model.urls.length; urlCount++){
			if(byId('network-url-input-' + urlCount) == null){
				addInput('network-url-', urlCount);
			}
			byId('network-url-input-' + urlCount).value = model.urls[urlCount];
		}
	}

	byId('network-appropriate-content').checked = model.appropriateContent;
	byId('network-appropriate-content').disabled = !isNewNetwork;

	if(!isNewNetwork){
		var networkManagerSelect = byId('network-manager-select');
		networkManagerSelect.options.length = 0;
		for (var count = 0; count < model.ownedNetworks.length; count++) {
			var ownedNetwork = model.ownedNetworks[count];
			addOption(networkManagerSelect, ownedNetwork.name, ownedNetwork.id, (ownedNetwork.id == model.network));
		}
	}
}

function displayNetworkDesignModel(model){
	var state = window.state;
	if (state == null) {
		state = new Object();
		window.state = state;
	}
	state.model = model;

	setRadioValue('network-skin-type-', (model.borderType != null) ? model.borderType : 'Gordo')

	setSelect('network-load-sequence', (model.loadSequence != null) ? model.loadSequence : 'widget');

	byId('network-manager-color-0').value = (model.footerColor != null ) ? model.footerColor : null;
	byId('network-manager-color-1').value = (model.footerFontColor != null ) ? model.footerFontColor : null;
	updateColorPreviews();

}

function displayNetworkTargetModel(model){
	var state = window.state;
	if (state == null) {
		state = new Object();
		window.state = state;
	}

	model.networkWidgetsPage = 0;
	model.totalNetworkWidgets = (model.approvedWidgets != null) ? model.approvedWidgets.length : 0;

	state.model = model;

	displayNetworkWidgets();

	var count = 0
	var done = false;

	while(!done){
		var element = byId('target-network-category-include-' + count )
		if(element != null){
			isNetworkCategory = aryContains(model.categories, element.name);
			byId('target-network-category-include-' + count ).checked = isNetworkCategory;
			byId('target-network-category-exclude-' + count ).checked = !isNetworkCategory;
			count++;
		}else{
			done = true;
		}
	}

	byId('target-network-tags').value = (model.tags != null) ? model.tags.toString() : '';
}

function displayNetworkInstallModel(model){
	var state = window.state;
	if (state == null) {
		state = new Object();
		window.state = state;
	}

	model.networkWidgetsPage = 0;
	model.totalNetworkWidgets = (model.approvedWidgets != null) ? model.approvedWidgets.length : 0;
	state.model = model;

	displayNetworkWidgets();

	var approvedWidgetIds = new Array();

	var mrssWidgetSelect = byId('network-mrss-widgets');
	mrssWidgetSelect.options.length=0;

	if(model.approvedWidgets != null){
		for(var approvedWidgetIdx = 0; approvedWidgetIdx < model.approvedWidgets.length; approvedWidgetIdx++){
			var approvedWidget =  model.approvedWidgets[approvedWidgetIdx];
			approvedWidgetIds.push(approvedWidget.id);

			//add options to the mrss select
			addOption(mrssWidgetSelect, model.approvedWidgets[approvedWidgetIdx].title , model.approvedWidgets[approvedWidgetIdx].id, false);
		}
	}

	updateRss();

	if(model.matchingWidgets != null){
		var leftColSize =  Math.ceil(model.matchingWidgets.length / 2);
		var rightColSize = Math.floor(model.matchingWidgets.length - (model.matchingWidgets.length / 2));

		prepareRepeatedNodes('widget-entry-', leftColSize);
		prepareRepeatedNodes('widget-entry-right-', rightColSize);

		var idTemplate = 'widget-entry';
		for(var matchingWidgetIdx = 0; matchingWidgetIdx < leftColSize;  matchingWidgetIdx++){
			var widget = model.matchingWidgets[matchingWidgetIdx];
			setTextContent(idTemplate+'-name-'+matchingWidgetIdx, widget.title );
			byId(idTemplate+'-name-'+matchingWidgetIdx).href = 'javascript:displayWidgetPreview('+widget.id+');'
			byId(idTemplate+'-input-'+matchingWidgetIdx).value = widget.id;
			byId(idTemplate+'-input-'+matchingWidgetIdx).checked = (approvedWidgetIds.indexOf(widget.id) != -1);
		}

		idTemplate = 'widget-entry-right';
		for(var matchingWidgetIdx = 0; matchingWidgetIdx < rightColSize;  matchingWidgetIdx++){
			var widget = model.matchingWidgets[matchingWidgetIdx + leftColSize];
			setTextContent(idTemplate+'-name-'+matchingWidgetIdx, widget.title );
			byId(idTemplate+'-name-'+matchingWidgetIdx).href = 'javascript:displayWidgetPreview('+widget.id+');'
			byId(idTemplate+'-input-'+matchingWidgetIdx).value = widget.id;
			byId(idTemplate+'-input-'+matchingWidgetIdx).checked = (approvedWidgetIds.indexOf(widget.id) != -1);
		}
	}else{
		prepareRepeatedNodes('widget-entry-', 0);
	}


	hideIf('no-matching-widgets', (model.matchingWidgets != null && model.matchingWidgets.length > 0));

	byId('network-agree-to-terms').checked = model.agreeToTerms;
	byId('network-agree-to-terms').disabled = !isNewNetwork;

	if(model.agreeToTerms && model.appropriateContent){
		if(model.approvedWidgets != null && model.approvedWidgets.length > 0){
			byId('network-embed-code').disabled = false;
			flashvars = {
				"networkId": model.networkId
			};
			var contentWidth = getNetworkContentWidth(model.borderType);
			var embedCode = getWidgetEmbed(contentWidth , flashvars, model.borderWidth, model.borderHeight, model.borderType);
			byId('network-embed-code').value = embedCode;
		}else{
			byId('network-embed-code').value = 'There are no widgets currently in this Network. Please broaden your targeting criteria';
			byId('network-embed-code').disabled = true;
		}
	}else if(!model.agreeToTerms){
		byId('network-embed-code').value = 'You must agree to our Terms of Service and associated Licensing Agreements before we can provide you with the embed code for this Network';
		byId('network-embed-code').disabled = true;
	}else if(!model.appropriateContent){
		byId('network-embed-code').value = 'You must verify that the content on your site is not related to the sale of Tobacco, Alcohol, Firearms, Gambling or Pornography before we can provide you with the embed code for this Network. Go back to the "Describe" section.';
		byId('network-embed-code').disabled = true;
	}

	var demoUrl = 'http://cozmo.tv/main/demo.html?networkId='+model.networkId;
	byId('network-demo-url').href = demoUrl;

}

function updateRss(){
	var model = window.state.model;
	var widgetId = byId('network-mrss-widgets').value;
	byId('network-mrss').value = '';

	if(widgetId != null && widgetId != ""){
		wait(500);
		byId('network-mrss').value = 'http://cache.cozmo.tv/main/cozmo-mrss.xml?type=shows&networkId='+model.networkId+'&widgetId='+widgetId;
	}
}

function getNetworkContentWidth(borderType){
	if(borderType == 'Poco'){
		return 300;
	}else if(borderType == 'Flaco'){
		return 640;
	}else if(borderType == 'Gordo'){
		return 400;
	}else if(borderType == 'Sencillo'){
		return 400;
	}else if(borderType == 'Sencillo_HD'){
		return 400;
	}else{
		return 360;
	}
}

function displayNetworkWidgets(){
	var state = window.state;
	if (state != null && state.model != null && state.model.approvedWidgets != null && state.model.approvedWidgets.length > 0) {
		var model = state.model;
		var approvedWidgets = model.approvedWidgets;
		displayPage('network-widgets-page', model.networkWidgetsPage, 5, model.totalNetworkWidgets, gotoNetworkWidgetsPage);

		var approvedWidgetPage = getPage(approvedWidgets, model.networkWidgetsPage, 5);
		showIf('no-network-widgets', false);
		prepareRepeatedNodes('network-widget-', (approvedWidgetPage.length < 5) ? approvedWidgetPage.length : 5);
		for(var approvedWidgetIdx = 0 ; approvedWidgetIdx < approvedWidgetPage.length ; approvedWidgetIdx++){
			var widget = approvedWidgetPage[approvedWidgetIdx];
			setTextContent('network-widget-name-'+approvedWidgetIdx, widget.title);
			byId('network-widget-image-'+approvedWidgetIdx).src = (widget.imageId != null) ? 'media.html?id=' + widget.imageId : '../images/default-channel-icon.jpg';
			byId('network-widget-'+approvedWidgetIdx).onclick = new Function('displayWidgetPreview('+widget.id+');');
		}
	}else {
		prepareRepeatedNodes('network-widget-', 0);
		displayPage('network-widgets-page', 0, 5, 0, gotoNetworkWidgetsPage);
		showIf('no-network-widgets', true);
		return;
		//hide widget section....?
	}
}

function displayAffiliateTermsOfService(model){
	var date = new Date();
	setTextContent('date', date.toDateString());
	setTextContent('licensee', model.corporationName);
	setTextContent('corpType',model.corporationType);
	setTextContent('address',model.address);
	setTextContent('address2',model.address);
	setTextContent('name', model.firstName + ' ' + model.lastName);
	setTextContent('title', model.title);
	setTextContent('fax', model.fax);
	setTextContent('email', model.email);
}

function displayWidgetQueries(model) {
	var state = window.state;

    if(model != null){
        if(state.model.widgetId == model.widgetId){
			model.queryIds = state.model.queryIds; //preserve state across paging
		}
		state.model = model;
    }else{
        model = state.model;
    }

    var queries = model.tabQueries;

	var base = model.tabQueriesPage*10;
	var num = Math.min(10,model.totalTabQueries-base);

	setSelect('library-channel-select', (model.libraryCategory != null) ? model.libraryCategory : 'none');
	displayActiveTab('query-selection-tab-', 5, model.tabIndex)

	prepareRepeatedNodes('query-selection-div-0',num);

	for (var count = 0; count < num; count++) {
		var query = queries[count];
		var selected = aryContains(model.queryIds, query.id);
		var isFavorite = aryContains(model.favoriteQueryIds, query.id);

		setTextContent('query-selection-title-'+count, query.name);
		byId('query-selection-title-'+count).href ='javascript:openPreviewQueryDialog('+query.id+');';

		setTextContent('query-selection-author-'+count, query.authorName);

		setTextContent('query-selection-url-'+count, (query.authorLink != null) ? query.authorLink : '');
		byId('query-selection-url-'+count).href = (query.authorLink != null) ? query.authorLink : '';
		setTextContent('query-selection-author-mojo-'+count, query.authorMojo);
		setTextContent('query-selection-total-shows-'+count, query.totalShows);

		var hasMore = (query.description != null && query.description.length > 200);
		setTextContent('query-selection-short-description-text-'+count, truncateAry(query.description, 205));
		setTextContent('query-selection-detailed-description-text-'+count, query.description);
		setClassName('query-selection-description-div-'+count,'show-short-description');
		showIf('query-selection-more-href-'+count, hasMore);
		byId('query-selection-more-href-'+count).href = 'javascript:setClassName(\'query-selection-description-div-'+count+'\',\'show-detailed-description\')';
		byId('query-selection-less-href-'+count).href = 'javascript:setClassName(\'query-selection-description-div-'+count+'\',\'show-short-description\')';

		var queryImg = byId('query-selection-thumb-img-'+count);
		queryImg.src = query.imageUrl;

		var orderInput = byId('query-selection-lineup-number-input-'+count);
		orderInput.value = (selected) ? aryFind(model.queryIds, query.id) + 1 : '';
		orderInput.onchange= new Function ('changeQueryOrder('+query.id+', \''+orderInput.id+'\');');

		var checkbox = byId('query-selection-lineup-checkbox-'+count);
		checkbox.checked = selected;
		checkbox.onclick = new Function('toggleQuery('+query.id+',  \''+orderInput.id+'\');');

		showIf('query-selection-edit-span-'+count, (model.userId == query.ownerId));
		byId('query-selection-edit-href-'+count).href = jsEscape('manage-channels2.html?channelId='+query.channelId);

		showIf('query-selection-rss-img-'+count, (query.type == 'Feed'))

		byId('query-selection-related-href-'+count).href ='javascript:gotoChannelSearch(\''+jsEscape(query.name)+'\');';

		byId('query-selection-favorite-href-'+count).href ='javascript:saveQuery('+ query.id +', '+ !isFavorite +');';
		setTextContent('query-selection-favorite-href-'+count, (isFavorite) ? 'Remove from Favorites' : 'Add to Favorites');

		prepareChildList('query-selection-tags-'+count, query.tags.length, 'query-selection-tag-'+count+'-0', 'a' );

		for(var tagIdx = 0; tagIdx < query.tags.length; tagIdx++){
			setTextContent('query-selection-tag-'+count+'-'+tagIdx, query.tags[tagIdx]);
			byId('query-selection-tag-'+count+'-'+tagIdx).href ='javascript:gotoChannelSearch(\''+jsEscape(query.tags[tagIdx])+'\');';
			if(tagIdx <  query.tags.length-1){
				insertTextAfter('query-selection-tag-'+count+'-'+tagIdx, ', ');
			}
		}

	}

    displayPage('query-upper-selection-page', model.tabQueriesPage, 10, model.totalTabQueries, gotoAdminQueriesPage);
    displayPage('query-lower-selection-page', model.tabQueriesPage, 10, model.totalTabQueries, gotoAdminQueriesPage);
}

function displayActiveTab(id, count, tabIdx){
	for(var idx = 0; idx < count; idx++ ){
		setClassName(''+ id + idx, (idx == tabIdx) ? 'selected-title-button' : 'enabled-title-button');
	}
}

function jsEscape(str) {
	return dojo.string.escapeJavaScript(str);
}

function htmlEscape(str) {
	var ret = (str != null) ? new String(str) : '';
	return dojo.string.escapeXml(ret);
}

function toggleQuery(id, orderInputId) {
	var state = window.state;
	var model = state.model;

	if(model.queryIds == null){
		model.queryIds = new Array();
	}

	var selected = aryContains(model.queryIds, id);
	if (selected) {
		aryRemove(model.queryIds, id);
		byId(orderInputId).value = '';
	} else {
		model.queryIds.push(id);
		byId(orderInputId).value = aryFind(model.queryIds, id) + 1;
	}
}

function toggleVideo(id, orderInputId) {
	var state = window.state;
	var model = state.model;
	var selected = aryContains(model.listingShowIds, id);
	if (selected) {
		aryRemove(model.listingShowIds, id);
		byId(orderInputId).value = '';
	} else {
		model.listingShowIds.push(id);
		byId(orderInputId).value = aryFind(model.listingShowIds, id) + 1;
	}
}

function changeLineupOrder(id, orderInputId) {
	var state = window.state;
	var model = state.model;
	var selected = aryContains(model.listingShowIds, id);
	var checkbox = byId(orderInputId);
	if (selected) {
		var order = parseInt(checkbox.value);
		if(order != 'NaN' && order > 0 && order <= model.listingShowIds.length){
			aryRemove(model.listingShowIds, id);
			aryInsert(model.listingShowIds, id, order - 1)
		}
	}
}

function changeQueryOrder(id, orderInputId) {
	var state = window.state;
	var model = state.model;
	var selected = aryContains(model.queryIds, id);
	var checkbox = byId(orderInputId);
	if (selected) {
		var order = parseInt(checkbox.value);
		if(order != 'NaN' && order > 0 && order <= model.queryIds.length){
			aryRemove(model.queryIds, id);
			aryInsert(model.queryIds, id, order - 1)
		}
	}
}

function aryInsert(ary, val, idx){
	ary.splice(idx, 0, val);
}

function aryRemove(ary, val) {
	var idx = aryFind(ary, val);
	if (idx >= 0) ary.splice(idx, 1);
}

function aryFind(ary, val) {
	if ((ary == null) || (val == null)) return -1;
	var len = ary.length;
	if ((len == null) || (!(len > 0))) return -1;

	for (var count = 0; count < len; count++) {
		if (ary[count] == val) return count;
	}

	return -1;
}

function truncateAry(ary, len){
	if((ary == null)  || (len == null)){
		return ary;
	}else if(len <= ary.length){
		var ret = ary.slice(0, len);
		var lastWhiteSpace = ret.lastIndexOf(' ');
		return ret.slice(0, lastWhiteSpace);
	}else{
		return ary;
	}

}

function aryContains(ary, val) {
	if (ary == null) return false;
	if (val == null) return false;
	var len = ary.length;
	if (len == null) return false;
	if (!(len > 0)) return false;
	for (var count = 0; count < len; count++) {
		if (ary[count] == val) return true;
	}
	return false;
}


function displayHeader(model) {
	var username = 'Guest';
	if (model != null && model.username != null) username = model.username;

	var userImageUrl =  (model != null && model.imageId != null) ? ('media.html?id=' + model.imageId) : "../images/guest.gif";

	var guest = (model == null || model.guest == true);

	setTextContent('username-span', username);
	byId('user-image').src = userImageUrl;
	showIf('login-span', guest, 'logout');
	hideIf('logout-span', guest, 'logout');
//	showIf('w-sign-in', guest);
}

function setButtonMode(mode, count){
	for(var divIdx = 0; divIdx < count; divIdx++){
		setClassName('submit-div-'+divIdx, mode);
	}
}

function resetInputs(templateId){
	var idx = 1;
	while(byId(templateId+idx)){
		removeById(templateId+idx);
		idx++;
	}

	prepareRepeatedNodes(templateId+'0', 1);
	setTextContent(templateId+'action-0', 'Add Another...');
	byId(templateId+'action-0').href = 'javascript:addInput(\''+templateId+'\','+ 1 +');';

	var parentNode = byId(templateId+0);
	var inputAry = parentNode.getElementsByTagName('input');
	for(var inputIdx = 0; inputIdx < inputAry.length; inputIdx++){
		var input = inputAry[inputIdx];
		input.value = '';
	}
}

function addInput(templateId, num){
	prepareRepeatedNodes(templateId+'0', num+1);

	var parentNode = byId(templateId+(num));

	//first fix up the new inputs...
	var inputAry = parentNode.getElementsByTagName('input');
	for(var idx = 0; idx < inputAry.length; idx++){
		var input = inputAry[idx];
		input.value = '';
		var name = input.name
		input.name = name.substring(0, name.length-1) + num;
	}

	var oldNum = (num-1);
	var oldActionId = templateId+'action-'+oldNum;

	setTextContent(oldActionId, 'x Delete');
	byId(oldActionId).href = 'javascript:removeInput(\''+templateId+'\', '+oldNum+');';

	var newActionId = templateId+'action-'+num;
	byId(newActionId).href = 'javascript:addInput(\''+templateId+'\','+(num + 1)+');';
}

function removeInput(templateId, oldNum){
	removeById(templateId+oldNum)

	var idx = ++oldNum;
	while(byId(templateId+idx)){

		var newIdx = (idx -1);
		dojo.lang.forEach(getNodeAndDescendants(byId(templateId+idx)), function(n){
			var oldId = n.id;
			var newId = numberId(oldId,newIdx+'');
			n.id=newId;
		});

		setTextContent(templateId+'action-'+newIdx, 'x Delete');
		byId(templateId+'action-'+newIdx).href = 'javascript:removeInput(\''+templateId+'\', '+newIdx+');';

		var parentNode = byId(templateId+newIdx);

		var inputAry = parentNode.getElementsByTagName('input');
		for(var inputAryIdx = 0; inputAryIdx < inputAry.length; inputAryIdx++){
			var input = inputAry[inputAryIdx];
			var name = input.name
			input.name = name.substring(0, name.length-1) + newIdx;
		}

		idx++;
	}

	setTextContent(templateId+'action-'+(idx - 2), 'Add Another...');
	byId(templateId+'action-'+(idx - 2)).href = 'javascript:addInput(\''+templateId+'\','+(idx - 1)+');';

}