var disabledSelects = [];
var activePopup = null;
var activePopupScrollable = true;
var activePopupFixed = false;
var overlayDissableOnPopup = null;

function initCookies() {
	var referrer = new String(document.referrer);
	referrer = (referrer.indexOf(document.location.host) != -1)? '<direct>': document.referrer;
	var uri = new URI(document.location);
	var adReferrer = uri.getData('ad');
	var affid = uri.getData('affid');
	if(!adReferrer) {
		adReferrer = '<direct>';
	}
	if(!Cookie.read('ref1')) {
		setCookie('ref1', referrer, 3);
		setCookie('ref2', '<first access>', 3);
	}
	else if(referrer != 'local') {
		setCookie('ref2', referrer, 3);
	}
	if(!Cookie.read('ad_ref1')) {
		setCookie('ad_ref1', adReferrer, 3);
		setCookie('ad_ref2', '<first access>', 3);
	}
	else if(adReferrer != 'local') {
		setCookie('ad_ref2', adReferrer, 3);
	}
	if(!Cookie.read('affid')) {
		setCookie('affid', uri.getData('affid'), 1);
	}
}

function setCookie(name, value, duration) {
	var date = new Date();
	date = new Date(date.getFullYear(), date.getMonth() + duration, date.getDate());
	document.cookie = name + '=' + escape(value) + '; expires=' + date.toGMTString();
}

function getCookie(cName)
{
	if(document.cookie.length > 0)
	{
		cStart = document.cookie.indexOf(cName + "=");
		if(cStart != -1)
		{
			cStart = cStart + cName.length + 1;
			cEnd = document.cookie.indexOf(";",cStart);
			if(cEnd == -1)
			{
				cEnd = document.cookie.length;
			}
			return unescape(document.cookie.substring(cStart,cEnd));
		}
	}
	return "";
}


function initLinksTarget() {
	$$('a[rel=nofollow]').setProperty('target', '_blank');
        $$('a[rel=newwindow]').setProperty('target', '_blank');
}

function initChatLink() {
	$$('.chat-link').addEvent('click', function(event) {
		event.stop();
		openChatPopup($(this).getProperty('href'));
	});
}

var clearDone = false;

function clearClientPopup(){
	if(clearDone) return 1;
	$$('.client-popup-link').each(function(el){
		var parent = el.getParent();
		var _href = el.href;
		parent.removeChild($(el));
		new Element('a', {href: _href}).inject(parent);
	});
	clearDone = true;
}

function initClientPopup() {
        var clientPopup = $('client-popup');
        if(clientPopup) {
            $$('.client-popup-link').addEvent('click', function(event) {
            event.stop();
            showPopup('client-popup');
            });
            var clientPopupClose = $('client-popup-close');
            if(clientPopupClose) {
                    clientPopupClose.addEvent('click', function(event) {
                            event.stop();
                            hidePopup();
                    });
            }
            var clientResponse = $('client-response');
            var clientForgotResponse = $('client-forgot-response');
            if((clientResponse && clientResponse.get('html')) || (clientForgotResponse && clientForgotResponse.get('html'))) {
                    showPopup('client-popup');
            }
        }
}

function initImplementationPopup() {
	$$('.implementation-popup-link').addEvent('click', function(event) {
		event.stop();
		showPopup('popup-implementation');
	});
	var implementationPopupClose = $('implementation-popup-close');
	if(implementationPopupClose) {
		implementationPopupClose.addEvent('click', function(event) {
			event.stop();
			hidePopup();
		});
	}
	var implementationPopup = $('popup-implementation');
	if(implementationPopup)
	{
		implementationPopup.getElements('.tabset a').addEvent('click', function(event){
			$(this).getParent().getParent().getElements('li').removeClass('active');
			$(this).getParent().addClass('active');
			var pos = -1;
			if(pos = $(this).href.indexOf("#"))
			{
				var _target = $(this).href.substring(pos+1, $(this).href.length);
				if($(_target))
				{
					$(_target).getParent().getElements('.tabcontent').addClass('hidden');
					$(_target).removeClass('hidden');
				}
			}
			repositionPopup();
			return false;
		});
	}
}

function initPartnerPopup() {
	$$('.partner-popup-link').addEvent('click', function(event) {
		event.stop();
		showPopup('partner-popup');
	});
	var partnerPopupClose = $('partner-popup-close');
	if(partnerPopupClose) {
		partnerPopupClose.addEvent('click', function(event) {
			event.stop();
			hidePopup();
		});
	}
	var partnerResponse = $('partner-response');
	var partnerForgotResponse = $('partner-forgot-response');
	if((partnerResponse && partnerResponse.get('html')) || (partnerForgotResponse && partnerForgotResponse.get('html'))) {
		showPopup('partner-popup');
	}
}

function initNewPartnerPopup() {
	var newPartnerResponse = $('partner-register-response');
	if(newPartnerResponse) {
		overlayDissableOnPopup = true;
		showPopup('confirmation-popup');
	}
}

function openChatPopup(url) {
	var chatPopup = window.open(url, 'CHAT', 'width=458,height=615,toolbar=no,status=no,scrollbars=no,menubar=no,resizable=no');
	if(chatPopup) {
		try {
			chatPopup.focus();
		}
		catch(e) {};
	}
}

function openChatHistoryPopup(url) {
	var chatHistoryPopup = window.open(url, 'HISTORY', 'width=900,height=347,toolbar=no,status=no,scrollbars=no,menubar=no,resizable=no');
	if(chatHistoryPopup) {
		try {
			chatHistoryPopup.focus();
		}
		catch(e) {}
	}
}

function parentWindowOpen(href) {
	var opener;
	if(window.opener) {
		if(window.opener.opener) {
			opener = window.opener.opener;
		}
		else {
			opener = window.opener;
		}
		opener.location = href;
	}
	else {
		opener = window.open(href);
	}
	try {
		opener.focus();
	}
	catch(e) {};
}

function initTrustGuard() {
	var trustGuard = $('trust-guard');
	if(trustGuard) {
		trustGuard.addEvent('click', function(event) {
			event.stop();
			var nonwin = navigator.appName != 'Microsoft Internet Explorer'? 'yes':'no';
			window.open(this.href, 'welcome', 'location=' + nonwin + ',scrollbars=yes,width=517,height=' + screen.availHeight + ',menubar=no,toolbar=no');
		});
	}
}

function initVerisignSecured() {
	var verisignSecuredElement = $('verisign-secured');
	if(verisignSecuredElement) {
		verisignSecuredElement.addEvent('click', function(event) {
			event.stop();
			var nonwin = navigator.appName != 'Microsoft Internet Explorer'? 'yes':'no';
			window.open('https://sealinfo.verisign.com/splash?form_file=fdf/splash.fdf&dn=WWW.PSD2HTML.COM&lang=en', 'welcome', 'location=' + nonwin + ',scrollbars=yes,width=517,height=442,menubar=no,toolbar=no');
		});
	}
}

function isDst(date) {
	var summerDate = new Date(date.getFullYear(), 6, 1);
	return summerDate.getTimezoneOffset() == date.getTimezoneOffset();
}

function getDstOffset() {
	var d = new Date();
	var winter = new Date(d.getFullYear(), 0, 1);
	var summer = new Date(d.getFullYear(), 6, 1);
	var winterOffset = -winter.getTimezoneOffset();
	var summerOffset = -summer.getTimezoneOffset();
	return summerOffset - winterOffset;
}

function getGmtOffset() {
	var d = new Date();
	var winter = new Date(d.getFullYear(), 0, 1);
	var summer = new Date(d.getFullYear(), 6, 1);
	var winterOffset = -winter.getTimezoneOffset();
	var summerOffset = -summer.getTimezoneOffset();
	return (winterOffset < summerOffset)? winterOffset: summerOffset;
}

function setGmtOffset(elementId) {
	var gmtOffsetElement = $(elementId);
	if(gmtOffsetElement) {
		gmtOffsetElement.setProperty('value', getGmtOffset());
	}
}

function getPageScroll() {
	var pageScroll;
	if(self.pageYOffset) {
		pageScroll = self.pageYOffset;
	} else if(document.documentElement && document.documentElement.scrollTop) { // Explorer 6 Strict
		pageScroll = document.documentElement.scrollTop;
	} else if(document.body) { // all other Explorers
		pageScroll = document.body.scrollTop;
	}
	return pageScroll;
}

function getPageSize() {
	var xScroll, yScroll;
	var windowWidth, windowHeight;
	if(window.innerHeight && window.scrollMaxY) {
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if(document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	if(self.innerHeight) { // all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if(document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if(document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight) {
		pageHeight = windowHeight;
	} else {
		pageHeight = yScroll;
	}
	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth) {
		pageWidth = xScroll;
	} else {
		pageWidth = windowWidth;
	}
	arrayPageSize = new Array(pageWidth, pageHeight, windowWidth, windowHeight, xScroll, yScroll);
	return arrayPageSize;
}

function initOverlay() {
	var overlayElement = $('overlay');
	if(overlayElement) {
		overlayElement.setStyles({
			'position': 'absolute',
			'left': 0,
			'top': 0,
			'opacity': 0.6,
			'background': '#000',
			'z-index': 200
		});
		resizeOverlay();
		hideOverlay();
		overlayElement.addEvent('click', function() {
			if(activePopup) {
				if(!overlayDissableOnPopup) {
					hidePopup();
				}
			}
			else {
				hideOverlay();
			}
		});
		document.addEvent('keydown', function(event) {
			if(activePopup && event.key == 'esc') {
				hidePopup();
			}
			return true;
		});
	}
}

function showOverlay() {
	var overlayElement = $('overlay');
	if(overlayElement) {
		overlayElement.removeClass('hidden');
		resizeOverlay();
	}
}

function hideOverlay() {
	var overlayElement = $('overlay');
	if(overlayElement) {
		overlayElement.addClass('hidden');
	}
}

function resizeOverlay() {
	var overlayElement = $('overlay');
	if(overlayElement) {
		var arrayPageSize = getPageSize();
		overlayElement.setStyles({
			'width': (arrayPageSize[4] + 'px'),
			'height': (arrayPageSize[1] + 'px')
		});
	}
}

function showPopup(popupId, scrollable, fixed) {
	var popupElement = $(popupId);
	if(popupElement) {
		if(Browser.Engine.trident4) {
			disabledSelects.empty();
			$$('#main select').each(function(item) {
				item.setStyle('visibility', 'hidden');
				disabledSelects.push(item);
			});
		}
		showOverlay();
		activePopup = popupElement;
		activePopupScrollable = (scrollable != false);
		activePopupFixed = !Browser.Engine.trident4 && (fixed != false);
		popupElement.setStyles({
			'position': (activePopupFixed)?'fixed':'absolute',
			'left': 0,
			'top': 0,
			'z-index': 999
		});
		popupElement.removeClass('hidden');
		repositionPopup();
	}
}

function hidePopup() {
	if(activePopup) {
		if(Browser.Engine.trident4) {
			disabledSelects.each(function(item) {
				item.setStyle('visibility', 'visible');
			});
			disabledSelects.empty();
		}
		activePopup.addClass('hidden');
		hideOverlay();
		activePopup = null;
		activePopupScrollable = true;
		activePopupFixed = false;
		window.fireEvent('resize');
	}
}

function repositionPopup() {
	if(activePopup) {
		var popupCoords = activePopup.getCoordinates();
		var delta = getWidth() - popupCoords.width;
		if(delta > 0) {
			var left = Math.round(delta / 2);
		}
		else {
			var left = 0;
		}
		var delta = getHeight() - popupCoords.height;
		if(delta > 0) {
			var top = Math.round(delta / 2) + ((activePopupFixed)?0:getScrollTop());
		}
		else {
			var top = 0;
		}
		activePopup.setStyles({
			'left': left,
			'top': top
		});
	}
}

function detectSafariVersion() {
	if(navigator.appVersion.indexOf("Safari") != -1) {
		if(!window.getComputedStyle) {
			document.body.className += " safari2"
		}
		else {
			document.body.className += " safari3";
		}
	}
}

function detectBrowser() {
	var cssFix = function() {
		var u = navigator.userAgent.toLowerCase(),
		addClass = function(el,val) {
			if(!el.className) {
				el.className = val;
			} else {
				var newCl = el.className;
				newCl+=(" "+val);
				el.className = newCl;
			}
		},
		is = function(t){return (u.indexOf(t)!=-1)};
		addClass(document.getElementsByTagName('html')[0],[
			(!(/opera|webtv/i.test(u))&&/msie (\d)/.test(u))?('ie ie'+RegExp.$1)
			:is('firefox/2')?'gecko ff2'
			:is('firefox/3')?'gecko ff3'
			:is('gecko/')?'gecko'
			:is('chrome/')?'chrome'
			:is('opera/9')?'opera opera9':/opera (\d)/.test(u)?'opera opera'+RegExp.$1
			:is('konqueror')?'konqueror'
			:is('applewebkit/')?'webkit safari'
			:is('mozilla/')?'gecko':'',
			(is('x11')||is('linux'))?' linux'
			:is('mac')?' mac'
			:is('win')?' win':''
		].join(" "));
	}();
}

function isEnv(env)
{
	var _html = document.getElementsByTagName('html');
	if(_html[0])
	{
		var htmlClass = _html[0].className;
		return htmlClass.indexOf(env) != -1;
	}
	return false;
}

var _protocol = (("https:" == document.location.protocol) ? "https://" : "http://");
var _path = (("https:" == document.location.protocol) ? "secure-online" : "online");
var _pingUrl = _protocol + document.location.host + '/' + _path + '.html';

function ping() {
	new Request({
		url: _pingUrl,
		onComplete: function(response){
			var _loc = window.location.toString();
			if(_loc.indexOf('order-now') != -1 || response == 'ok') {
				setTimeout("ping()", 420000);
			}
		}
	}).send();
}

function initSubmitHover() {
	$$('input.btn-hover').addEvents({
		'mouseover': function() {
			var item = $(this);
			item.setProperty('src', item.getProperty('src').replace('-hover.gif', '.gif'));
			item.setProperty('src', item.getProperty('src').replace('.gif', '-hover.gif'));
		},
		'mouseleave': function() {
			var item = $(this);
			item.setProperty('src', item.getProperty('src').replace('-hover.gif', '.gif'));
		}
	});
}

function setCursor()
{
	var textarea = $('reply-message');
	if(!textarea) return;
	textarea.focus();
}

function closeRegisterPartnerPopup()
{
	var closeLink = $('new-partner-popup-close');
	if(!closeLink) return;
	closeLink.addEvent('click', function(){
		hidePopup();
		hideOverlay();
	});
}

function preloadMainImages() {
	var imagesPath = '/css/images/';
	var images = [
		imagesPath + 'bg-popup-corners.png?48',
		imagesPath + 'main-sprite.gif?48',
		imagesPath + 'popups-sprite.gif?48',
		imagesPath + 'bg-f-text.gif?48',
		imagesPath + 'bg-input-file.gif?48',
		imagesPath + 'bg-popup-corners.png'
	];
	new Asset.images(images);
}

function fixPhone() {
	$$('#top-panel li.tel span.disable').set('html','&nbsp;');
}

function initSmoothScroll()
{
	$$('#content-row div.arrow a').each(function(el){
		if(el.href.indexOf("#content-row") != -1)
		{
			el.addEvent('click', function(){
				new Fx.Scroll(window, {'duration': 400}).toElement('content-row');
				return false;
			});
		}
	});
}

function showEmptyFacebookBlogPopup()
{
    var count = 0;
    var holder = $$('.fb_share_count_inner');
    $each(holder, function(el) {
        if(el.get('html') == '&nbsp;' || el.get('html') == '') {
            var parent = el.getParent();
            if(parent) {
                parent.removeClass('fb_share_no_count');
                var sibling = parent.getPrevious();
                if(sibling) {
                    sibling.removeClass('fb_share_no_count');
                }
            }
            el.removeClass('fb_share_no_count');
            el.set('html', '0');
            var mainHolder = el.getParent('li.facebook');
            if(mainHolder) {
                if(mainHolder.getStyle('visibility') == '' || mainHolder.getStyle('visibility') == 'hidden') {
                   count++;
                }
                mainHolder.setStyle('visibility', 'visible');
            }
        }
        else {
            var mainHolder = el.getParent('li.facebook');
            mainHolder.setStyle('visibility', 'visible');
        }
    });

    if(count > 0) {
        setTimeout("showEmptyFacebookBlogPopup()", 500);
    }
}

function hideNeedABanner()
{
    var target = $('banner-link');
    if(!target) return;
    var size = window.getSize();
    if(size != 'undefined') {
        if(size.x >= 1250) {
            target.setStyle('display', 'block');
        }
        else {
            target.setStyle('display', 'none');
        }
    }
}

function initSlideStar(){
	var _speed = 500;
        var _hold = $('ribbon');
        if(!_hold) return;
        var _box = _hold.getElement('div.hold');
        var _box2 = _hold.getElement('div.hold > ul');
        var _link = _hold.getElement('a.open');
        var _timer;
        var _fbLink = _hold.getElement('div.hold > ul > li > a.ribbon-fb');
        if (_box && _box2 && _link){
            var _h = _box2.offsetHeight +2;
            _box.set('styles', {
                    'marginTop': -_h
            });
            _box.moo = new Fx.Tween(_box, {
                    duration: _speed,
                    link:'cancel'
            });
            _link.addEvent('click', function(){
                if (_hold.hasClass('close')){
                    _box.moo.start('marginTop', 0);
                    _hold.removeClass('close');

                }
                else{
                    _box.moo.start('marginTop', -_h);
                    _hold.addClass('close');
                }
                return false;
            });
            _box.addEvent('mouseenter',function(){
                if(_timer) clearTimeout(_timer);
            });
            _box.addEvent('mouseleave',function(){
                if(_timer) clearTimeout(_timer);
                _timer = setTimeout(function(){
                    _box.moo.start('marginTop', -_h);
                    _hold.addClass('close');
                },3000);
            })


        }
        _fbLink.addEvent('click', function(){
            var link = $(this).getProperty('href');
            window.open(link, "Facebook", "width=1050,height=650");
	    return false;
        });
}

function hideSocialRibbon()
{
    var target = $('ribbon');
    if(!target) return;
    var size = window.getSize();
    if(size != 'undefined') {
        if(size.x < 1021) {
            target.setStyle('display', 'none');
        }
        else {
            target.setStyle('display', 'block');
        }
    }
}

function initLikeButton()
{
    var holder = $('like-btn');
    if(!holder) return;
    var src = "https:" == document.location.protocol ? "https://" : "http://";
    holder.set('html', '<iframe src="'+src+'www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.psd2html.com&amp;layout=standard&amp;show_faces=false&amp;width=250&amp;action=like&amp;font=arial&amp;colorscheme=dark&amp;height=65" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:250px; height:65px;" allowTransparency="true"></iframe>');
}

window.addEvent('scroll', function() {
	resizeOverlay();
	if(activePopupScrollable) {
		repositionPopup();
	}
});

window.addEvent('resize', function() {
	resizeOverlay();
	repositionPopup();
        hideNeedABanner();
        hideSocialRibbon();
});

window.addEvent('domready', function() {
    showEmptyFacebookBlogPopup();
	initSmoothScroll();
	preloadMainImages();
	fixPhone();
	detectBrowser();
	detectSafariVersion();
	initCookies();
	initLinksTarget();
	initChatLink();
	initTrustGuard();
	initVerisignSecured();
	initOverlay();
	initClientPopup();
	initPartnerPopup();
	initNewPartnerPopup();
	closeRegisterPartnerPopup();
	initSubmitHover();
    hideNeedABanner();
	initSlideStar();
	hideSocialRibbon();
	initLikeButton();
	setTimeout("ping()", 420000);
	initImplementationPopup();
	initFbsShare();
});

//google functions
function _uGC(l,n,s)
{
	if (!l || l=="" || !n || n=="" || !s || s=="") return "-";
	var i,i2,i3,c="-";
	i=l.indexOf(n);
	i3=n.indexOf("=")+1;
	if (i > -1) {
	   i2=l.indexOf(s,i); if (i2<0) { i2=l.length; }
	   c=l.substring((i+i3),i2);
	}
	return c;
}
function checkFirstVisit()
{
	var _cookie = " " + document.cookie + ";";
	if(_cookie.indexOf("__utma=") == -1)
	{
		return true;
	}
	else
	{
		return false;
	}
}
function grabFirstReferrer()
{
	var z = _uGC(document.cookie, "__utmz=", ";");
	var urchinSource = _uGC(z,"utmcsr=", "|");
	var gclid = _uGC(z,"utmgclid=","|");
	if(gclid != "-")
	{
		urchinSource = "google";
	}
	pageTracker._setVar(urchinSource);
}

function initFbsShare()
{
	$$('a.facebook-share').addEvent('click', onClickFbsShare);
}

function onClickFbsShare()
{
	var _url = location.href;
	if(this.rel)
	{
		_url = this.rel;
	}
	var _title = document.title;
	if(this.rev)
	{
		_title = this.rev;
	}
	window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(_url)+'&t='+encodeURIComponent(_title),'sharer','toolbar=0,status=0,width=626,height=436');
	return false;
}
