var sitename = ' @ Martin Ivanov';
var loaddelay = '4000';
var site = {};
var siteenginescriptsroot = '';
var datafile = siteenginescriptsroot + 'Scripts/Data.xml';
var datafiledoc;
var isSafari = navigator.userAgent.toLowerCase().indexOf('webkit') > -1;
var isIE = window.ActiveXObject;
var isFireFoxOrOpera = document.implementation && document.implementation.createDocument;
var isIE6 = /msie|MSIE 6/.test(navigator.userAgent) && !/msie|MSIE 8/.test(navigator.userAgent);

site.initialize = function () {
	if (window != top)
	top.location.href = location.href;
    if (window.addEventListener) {
        window.addEventListener('load', function (a) {
            loaddefaults();
        },
        false)
    }
    if (window.ActiveXObject) {
        window.attachEvent('onload', function (a) {
            loaddefaults();
        })
    }
};

function loaddefaults()
{
	render();
	initSocialBookmarksJs();
	createMenuJs();
	tabstripxml.demand('Scripts/Tabstrip.XML/TabSets/SideBarTabStrip.xml');
	loadvotingpoll();
	if(isIE)
	{
		relExternal();
	}
	setInterval(function(e)
	{
		doCallBack('OnlineUsers/uo.php', 'usersonline');
	}, 1000);
	doCallBack('getcountry.php', 'country');
	
	if(isIE || navigator.appName == 'Netscape' && !isSafari)
	{
		attachDomEvent('AddBookMark', 'click', function(e)
		{
			bookmarksite(document.title, window.location);
		});
		$get('AddBookMark').parentNode.className = '';
	}
}

function relExternal()
{
	var externalLinks = document.getElementsByTagName("A"); 
	for (var i=0; i<externalLinks.length; i++) 
	{ 
		var externalLink = externalLinks[i]; 
		if (externalLink.getAttribute("href") && externalLink.getAttribute("rel") == "external")
		{
			externalLink.target = "_blank";
		}
	}
}

function loadvotingpoll()
{
	if(!isSafari)
	{
		tabstripxml.demand('Scripts/Tabstrip.XML/TabSets/SideBarVotingPoll.xml');
		
		window.setTimeout(function(e)
		{
			radiobuttonxml.demand('Scripts/RadioButton.XML/RadioButtonLists/SideBarVotingPoll.xml');
		}, 2000);
		
		window.setTimeout(function(e)
		{
			var questionwrapper = document.getElementById('SideBarVotingPoll');
			var questionhead = document.getElementById('SideBarVotingPoll_tab_button_0').getElementsByTagName('SPAN')[2];
			var questiontext = questionwrapper.getElementsByTagName('legend')[0];
			questionhead.innerHTML = questiontext.innerHTML;
		}, 2500);

		window.setTimeout(function(e)
		{
			setDefaultValueToTheVotingPoll();
		}, 3500);
	}
	else
	{
		$get('VotingBooth').style.display = 'none';
		$get('SideBarVotingPoll').style.display = 'none';
	}
}

function defaultpage()
{
	loadPage('dev');
	if(isSafari)
	{
		setTimeout(function(e)
		{
			CreateGalleryJs('DefaultPageGallery', 'DropShadow');
		}, 2000);
	}
	else
	{
		setTimeout(function(e)
		{
			CreateGalleryJs('DefaultPageGallery', 'DropShadow');
		}, 100);
	}
}

function render()
{
	if(isIE6)
	{
		window.open('unsupported.php', '_self');
		//return false;
	}
	
	renderAjaxLoadingPanel();
	
	if(!document.location.hash)
	{
		defaultpage();
	}
	else
	{
		CheckHash();
	}

	attachDomEvent('dev_form', 'click', function(e)
		{
			filter('Forms');
		}
	);

	attachDomEvent('dev_ui', 'click', function(e)
		{
			filter('UI');
		}
	);
	
	attachDomEvent('dev_layout', 'click', function(e)
		{
			filter('Layout');
		}
	);

	attachDomEvent('dev_cm', 'click', function(e)
		{
			filter('CMS');
		}
	);

	attachDomEvent('dev_image', 'click', function(e)
		{
			filter('Images');
		}
	);
}

function showrecenturls()
{
	var recentpagesloader = $get('recently_visited').getElementsByTagName('UL')[0];
	var recentitems = recentpagesloader.getElementsByTagName('LI');
	var hashinput = $get('hash');
	var trimindex = 4;
	var trimat = document.title.split(' @');
	
	newitem = '<a href="#' + hashinput.value + '" title="' + trimat[0] + '" id="' + trimat[0] + '_recent" onclick="$insertFirstChild(this.parentNode.parentNode, \'LI\', this.parentNode.innerHTML); this.parentNode.parentNode.removeChild(this.parentNode)">' + trimat[0] + '</a>';
	
	if($get(trimat[0] + '_recent') == null)
	{
		$insertFirstChild(recentpagesloader, 'LI', newitem);

		for(var i = 0; i < recentitems.length; i ++)
		{
			if(i > trimindex)
			{
				$removeLastChild(recentpagesloader);
			}
		}
	}
}

function $insertFirstChild(element, newchildnodetagname, newchildnodecontent)
{
	var newchild = document.createElement(newchildnodetagname);

	newchild.innerHTML = newchildnodecontent;
	element.insertBefore(newchild, element.childNodes[0]);
}

function $removeLastChild(element)
{
	var lastchild = element.childNodes.length - 1;
	element.removeChild(element.childNodes[lastchild]);
}

function CheckHash()
{
	setInterval(function(e)
	{
		showrecenturls();
		var gethash = document.location.hash;
		var pagehash = gethash.split('#')[1];
		var currenthash = $get('hash');
		if(pagehash != currenthash.value)
		{
			if(pagehash == 'dev')
			{
				defaultpage();
				return false;
			}
			if(pagehash == 'contact')
			{
				loadPage(pagehash);
				window.setTimeout(function(e)
				{
					renderContactFormJs();
				}, 1000);
				return false;
			}
			if(pagehash == 'mp3')
			{
				loadPage(pagehash);
				window.setTimeout(function(e)
				{
					tabstripxml.demand('Scripts/Tabstrip.XML/TabSets/MusicTabStrip.xml');
				}, 1000);
			}
			if(pagehash == 'legacy')
			{
				loadPage(pagehash);
				window.setTimeout(function(e)
				{
					doCallBack('acidjslegacy.php', 'directory');
				}, 1000);
				window.setTimeout(function(e)
				{
					clearExtension('directory', 'exe', 'A');
				}, 1500);
				return false;
			}
			if(pagehash == 'manuals')
			{
				loadPage(pagehash);
				window.setTimeout(function(e)
				{
					doCallBack('manuals.php', 'manuals');
				}, 1000);
				window.setTimeout(function(e)
				{
					clearExtension('manuals', 'pdf', 'A');
					clearExtension('manuals', 'txt', 'A');
				}, 1500);
				return false;
			}
			if(pagehash == 'jsroutines')
			{
				loadPage(pagehash);
				window.setTimeout(function(e)
				{
					if($get('JavaScriptRoutinesShowAll') != null)
					{
						doCallBack('javascriptroutines.php', 'routines');
					}
				}, 2000);
				window.setTimeout(function(e)
				{
					if($get('JavaScriptRoutinesShowAll') != null)
					{
						checkboxxml.demand('Scripts/CheckBox.XML/CheckBoxLists/ToggleRoutines.xml');
					}
				}, 2600);
				window.setTimeout(function(e)
				{
					if($get('JavaScriptRoutinesShowAll') != null)
					{
						clearExtension('routines', 'html', 'BUTTON');
					}
				}, 2700);
				return false;
			}
			if(pagehash == 'bundle')
			{
				loadPage(pagehash);
				window.setTimeout(function(e)
				{
					if($get('CreativeBundle') != null)
					{
						checkboxxml.demand('Scripts/CheckBox.XML/CheckBoxLists/CreativeBundle.xml');
						checkboxxml.demand('Scripts/CheckBox.XML/CheckBoxLists/CreativeBundleToggle.xml');
					}
				}, 2600);
				return false;
			}
			if(!pagehash)
			{
				defaultpage();
				return false;
			}
			else
			{
				loadPage(pagehash);
				return false;
			}
		}
	}, 500);
}

function clearExtension(loader, ext, element)
{
	var a = $get(loader);
	var b = a.getElementsByTagName(element);
	var c = '.' + ext;

	for(var i = 0; i < b.length; i ++)
	{
		if(b != 'INPUT' || b != 'TEXTAREA')
		{
			b[i].innerHTML = b[i].innerHTML.replace(c, '');
			b[i].title = b[i].title.replace(c, '');
		}
		else
		{
			b[i].value = b[i].value.replace(c, '');
			b[i].title = b[i].title.replace(c, '');
		}
	}
}

function loadPage(alias)
{
	window.open('#' + alias, '_self');
	$get('hash').value = alias;
	if(isSafari)
	{
		displayLoadingPanel();
		datafiledoc = new XMLHttpRequest();
		datafiledoc.open("GET", datafile, true);
		datafiledoc.send(null);
		datafiledoc.onreadystatechange = function()
		{
			if(datafiledoc.readyState == 4)
			{
				renderPage(alias);
				setTimeout(function(e)
				{
					hideLoadingPanel();
				}, 1000);
				loadinfopage();
			}
		};
	}

	else
	{
		if(isIE)
		{
			datafiledoc = new ActiveXObject("Microsoft.XMLDOM");
			displayLoadingPanel();
		}

		if(isFireFoxOrOpera)
		{
			datafiledoc = document.implementation.createDocument("","",null);
			displayLoadingPanel();
		}
		
		datafiledoc.async = false;
		datafiledoc.load(datafile);
		renderPage(alias);
		setTimeout(function(e)
			{
				hideLoadingPanel();
			}, 1000);
		loadinfopage();
	}
	window.scrollTo(0, 0);
	CheckHash();
}

function loadinfopage()
{
	if($get('DemoScreenShot'))
	{
		window.setTimeout(function(e)
		{
			CreateGalleryJs('DemoScreenShot', 'DropShadow', false);
		}, 1000);	
	}
	if($get('DesriptionRoundedCorner'))
	{
		window.setTimeout(function(e)
		{
			createRoundedCorners('DesriptionRoundedCorner', 'large', '#d7dfc7', yes, yes, yes, yes);
		}, 1000);
	}
	if($get('DownloadsCount'))
	{
		window.setTimeout(function(e)
		{
			var scriptid = $get('DownloadsCount').getAttribute('rel')
			$get('DownloadsCount').innerHTML = '<strong>1' + ccount_display(scriptid) + '</strong>';
		}, 1500);
	}
}

function renderPage(alias)
{
	var contentloader = $get('content');
	if(isSafari)
	{
		var bookmarksroot = datafiledoc.responseXML.getElementsByTagName('root')[0];
	}
	else
	{
		var bookmarksroot = datafiledoc.getElementsByTagName('root')[0];
	}

	var items = bookmarksroot.getElementsByTagName('page');
	for(var i = 0; i < items.length; i ++)
	{
		var pagealias = items[i].getAttribute('alias');
		if(pagealias == alias)
		{
			var title = items[i].getAttribute('title');
			var content = items[i].childNodes[0].nodeValue;
			var tagline = document.getElementsByTagName('H2')[0];
			
			document.title = title +  sitename;
			tagline.innerHTML = title;
			contentloader.innerHTML = content;
		}
	}
}

function $create(element)
{
	return document.createElement(element);
}

function $get(stringId)
{
	return document.getElementById(stringId);
}

function attachDomEvent(ElementId, EventType, ClientFunction)
{
	var ClientEventType;
	if(window.attachEvent)
	{
		ClientEventType = 'on' + EventType;
		document.getElementById(ElementId).attachEvent(ClientEventType, ClientFunction)
	}
	else
	{
		document.getElementById(ElementId).addEventListener(EventType, ClientFunction, false);
	}
}

function openURL(URL, Window)
{
	window.open(URL, Window);
}

function filter(controls)
{
	// Forms, UI, Layout, Image, Miscelaneous
	defaultpage();
	
	window.setTimeout(function(e)
	{
		var controlstreeitems = $get('DefaultPageGallery').getElementsByTagName('LI');
		var heading = document.getElementsByTagName('H3')[0];
		for (var i = 0; i < controlstreeitems.length; i ++ )
		{
			if(controlstreeitems[i].getAttribute('rel') != controls)
			{
				controlstreeitems[i].style.display = 'none';
			}
		}
		heading.innerHTML += ' | ' + controls;
		document.title = heading.innerHTML + sitename;
	}, 1000);	
}

function openGallery(URL)
{
	var width = '650';
	var height = '550';
	window.open(URL, '_blank', 'toolbar=0, scrollbars=0, location=0, statusbar=0, menubar=0, resizable=0, width=' + width + 'px, height=' + height + 'px, left=320, top=240');
}

function openVideoPopUp(VideoURL)
{
	window.open('http://www.acidmachine.com/Scripts/Tabstrip.XML/TabSets/Videos/' + VideoURL, 'videos', 'width=425, height=349, top=' + document.documentElement.offsetHeight/2 + ', left=' + document.documentElement.offsetWidth/2 + ', statusbar=0, resizable=0');
}

function loadext(URL, Ext)
{
	window.open(URL, Ext);
}

function doCallBack(serverfile, serverfileloader)
{ 
	var AJAX;
	try
	{   
		AJAX = new XMLHttpRequest();  
	}
	catch(e)
	{   
	try
	{     
		AJAX = new ActiveXObject("Msxml2.XMLHTTP");     
	}
	catch(e)
	{     
		try
		{ 
			AJAX = new ActiveXObject("Microsoft.XMLHTTP");       
		}
		catch(e)
		{       
			alert("Your browser does not support AJAX.");       
			return false;       
		}     
	}   
}

AJAX.onreadystatechange = function()
{
	if(AJAX.readyState == 4)
	{
		if(AJAX.status == 200)
		{
			$get(serverfileloader).innerHTML = AJAX.responseText;   
		}
		else
		{
			//alert("Error: " + AJAX.statusText + " " + AJAX.status);
		}
	}
	else
		{

		}
	}
	AJAX.open("get", serverfile, true);
	AJAX.send(null);
}

function $toggle(elementid, toggleproperty, togglefactor) 
{
	elementid = $get(elementid);
	try
	{
		if(toggleproperty == 'display')
		{
			elementid.style.display = (elementid.style.display == togglefactor ) ? "" : togglefactor;
		}
		if(toggleproperty == 'visibility')
		{
			elementid.style.visibility = (elementid.style.visibility == togglefactor ) ? "" : togglefactor;
		}
		else if(toggleproperty != 'display' && toggleproperty != 'visibility')
		{
			alert('Invalid toggleproperty value (' + toggleproperty + '). Choose either "display" or "visibility".');
			return false;
		}
	}
	catch(e)
	{
		alert('Invalid togglefactor value. It should be "block", "none", "visible" or "hidden".');
	}
}

function clickall()
{
	var wrapper = $get('routines');
	var clicklinks = wrapper.getElementsByTagName('BUTTON');
	var code = wrapper.getElementsByTagName('CODE');
	//var hideall = $get('JavaScriptRoutinesShowAll_List_Item_0_input');
	var showall = $get('JavaScriptRoutinesShowAll_List_Item_0_input');
	
	if(showall.checked)
	{
		for(var i = 0; i < clicklinks.length; i ++)
		{
			clicklinks[i].click();
			clicklinks[i].nextSibling.style.display = 'block';
			clicklinks[i].disabled = true;
		}
	}
	else
	{
		for(var i = 0; i < code.length; i ++)
		{
			code[i].style.display = 'none';
			clicklinks[i].disabled = false;
		}
	}
}

function loadplayer()
{
  var s1 = new SWFObject("Scripts/player.swf", "ply", "730", "970", "9", "#ffffff");
  s1.addParam("allowfullscreen", "false");
  s1.addParam("allowscriptaccess", "always");
  s1.addParam("wmode", "opaque");
  s1.addParam("flashvars", "file=Scripts/SongsPlaylist.xml&frontcolor=4a7b09&playlist=bottom");
  s1.write("mediaspace");
}

function bookmarksite(title,url)
{
	if (window.sidebar)
	window.sidebar.addPanel(title, url, "");
	else if(window.opera && window.print)
	{
		var elem = document.createElement('a');
		elem.setAttribute('href',url);
		elem.setAttribute('title',title);
		elem.setAttribute('rel','sidebar');
		elem.click();
	} 
	else if(document.all)
	window.external.AddFavorite(url, title);
}

function download(fileid)
{
	window.open('getfile.php?FileId=' + fileid, 'getfilewindow', 'width=700, height=400');
}

/* creative bundle functions begin */
function calculate()
{
	var retail = 10;
	var componentslist = $get('CreativeBundle').getElementsByTagName('UL')[0].getElementsByTagName('INPUT');
	var listed_price = $get('listed_price');
	var bundled_price = $get('bundled_price');
	var you_save = $get('you_save');
	var checkout = $get('checkout');
	var total_items = $get('total_items');
	var min_items = 3;
	var total_items = $get('total_items');
	var order_bundle_button = $get('order_bundle_button');

	listed_price.value = 0;
	you_save.value = 0;
	bundled_price.value = 0;
	total_items.value = 0;
	checkout.value = '';

	for(var i = 0; i < componentslist.length; i ++)
	{
		var single_item_listed_price_value = componentslist[i].value.split('|')[1];
		var single_item_name = componentslist[i].value.split('|')[0]; 
		
		if(componentslist[i].checked)
		{
			listed_price.value = parseInt(listed_price.value) + parseInt(single_item_listed_price_value);
			you_save.value = parseInt(you_save.value) + parseInt(retail);
			bundled_price.value = listed_price.value - you_save.value;
			checkout.value += single_item_name + '; \n';
			total_items.value = parseInt(total_items.value) + parseInt('1');
		}
		
		else
		{
			rendercheckboxlist.prototype.unchecksingle('CreativeBundleToggle', 0);
		}

		if(total_items.value < min_items)
		{
			order_bundle_button.disabled = true;
			order_bundle_button.className = 'disabled';
		}

		else
		{
			order_bundle_button.disabled = false;
			order_bundle_button.className = '';
		}
	}

	checkout.value += '\nTotal: ' + bundled_price.value;
}

function order()
{
	var send_order_message = 'This will send your order to WeMakeSites.NET and after it has been processed by our team you will receive a PayPal invoice for your items.\n\nPress "OK" to continue or "Cancel" to review your selection.';
	var missing_data_message = 'Cannot process form due to missing or incomplete required data. Please, check the "name" and "email" inputs.';
	var bundle_name = $get('bundle_name');
	var bundle_email = $get('bundle_email');
	var bundle_error = $get('bundle_error');
	var final_checkout = $get('final_checkout');
	var checkout = $get('checkout');
	
	if(bundle_name.value == '' || bundle_email.value == '' || bundle_email.value.indexOf('@') < 0 || bundle_email.value.split('@')[0] == '' || bundle_email.value.split('@')[1] == '' || bundle_email.value.indexOf('.') < 0 || bundle_email.value.split('.')[1] == '' || bundle_email.value.split('.')[0] == '')
	{
		bundle_error.style.display = 'block';
		bundle_error.innerHTML = missing_data_message;
	}
	
	else
	{
		if(confirm(send_order_message))
		{
			bundle_error.style.display = 'none';
			final_checkout.value = 'New Creative Web 2.0 Bundle has been ordered by ' + bundle_name.value + ' (' + bundle_email.value + '): \n\n' + checkout.value;
			sendBundleOrder();
		}
	}
}

function togglecreativebundleitems(element)
{
	if(element.checked)
	{
		rendercheckboxlist.prototype.checkall('CreativeBundle');
	}
	else
	{
		rendercheckboxlist.prototype.uncheckall('CreativeBundle');
	}
	calculate();
}

var http_bundle = createBundleRequestObject();

function createBundleRequestObject() 
{
	var ro_bundle;
	var browser_bundle = navigator.appName;
	if(browser_bundle == "Microsoft Internet Explorer")
		{
			ro_bundle = new ActiveXObject("Microsoft.XMLHTTP");
	}
	else
	{
		ro_bundle = new XMLHttpRequest();
	}
	return ro_bundle;
}

function sendBundleOrder() 
{
	var final_checkout = $get('final_checkout');
	var bundle_subject = 'New Creative Web 2.0 Bundle Order';
	
	http_bundle.open('get', 'bundle.php?msg='+final_checkout.value+'&subject='+bundle_subject+'&action=send');
	http_bundle.onreadystatechange = handleBundleVote;
	http_bundle.send(null);
}

function handleBundleVote() 
{
	if(http_bundle.readyState == 4)
	{
		window.setTimeout(function(e)
		{
			hideLoadingPanel();
			window.open('#bundlesent', '_self');
		}, 1000);
	}
	else
	{
		displayLoadingPanel();
	}
}
/* creative bundle functions end */

site.initialize();