var cookieDomain = '';
var ajaxURL = '/pw/ajax.xml';

function popinAdvert() {
	var div = dialogBox('interstitial_dialog',580,0,true);
	document.getElementById('interstitial_div').innerHTML = "<iframe src=\"/pw/interstitial.html\" width=566 height=500 frameborder=0 scrolling=no></iframe>";
}


/* login ajax */

function openLoginDialog(email_address) {
    if(!email_address) { email_address = ''; }
    
    var form = document.getElementById('login_dialog_form');
    if(form) { 
        form.reset();
        form.elements["email"].value = email_address;
    }
    
    if(document.getElementById('login_dialog_errors')) {
        document.getElementById('login_dialog_errors').innerHTML = '';
    }
    
    var div = dialogBox('login_dialog',500,0,true);
}

function sponsoredLogin() {
	setCookie('credentials',1,5);
	setCookie('credentials_sponsored',1,5);
    dialogBoxClose('');
    logInChanged();
}

function ajaxLogin(form) {
    document.getElementById('login_dialog_errors').innerHTML = 'logging in.';

    var params = $('#' + form).serialize();

    $.ajax({
        type: "POST",
        url: ajaxURL,
        data: params,
        dataType: "xml",
        success: function(xml) {
            var status = getXmlFirstChildData('status',xml);
            if(status == 'ok') {
                var credentials = getXmlFirstChildData('credentials',xml);
                setCookie('credentials',credentials,365);
          		setCookie('validated',1);
                dialogBoxClose('');
                logInChanged();
            }
            else {
                if(document.getElementById('login_dialog_errors')) {
                    document.getElementById('login_dialog_errors').innerHTML = status;
                }
                else {
                    alert('Login error ' + status);
                }
            }
        },
        error: function() {
            alert('Login could not contact server');
        }
    });
}


function ajaxValidateLogin() {
	var params = 'proc=validate_credentials';
    $.ajax({
        type: "POST",
        url: ajaxURL,
        data: params,
        dataType: "xml",
        success: function(xml) {
            var status = getXmlFirstChildData('status',xml);
          	if(status == 'ok') {
          		setCookie('validated',1);
          	}
          	else {
          		deleteCookie('credentials');
          	}
        },
        error: function() {
            alert('Login validation could not contact server');
        }
    });
}

/* cookies */

function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return decodeURIComponent(c.substring(nameEQ.length,c.length));
    }
    return null;
}

function setCookie(name,value,expiredays) {
    var cookie;
    cookie = name + "=" + escape(value);
    if(expiredays) {
        var d=new Date();
        d.setDate(d.getDate() + expiredays);
        cookie += ";expires=" + d.toGMTString();
    }
    cookie += ';path=/';
    if(cookieDomain) {
        cookie += ';domain=' + cookieDomain;
    }
    document.cookie = cookie;
}

function deleteCookie(name) {
    setCookie(name,"",-1);
}

/* dialog boxes */

var currentDialogBoxId = "";
var dialogCloseDestination = '';

/*    
    open a dialog box centered horizontally on the screen 30 pixels from the top
    'theId' is an hidden element (usually a DIV) defined somewhere in the document that defined the content of the dialog box
    if another dialog box is open it will be closed before opening the new one
    if 'modal' is true then the window will be greyed out and all clicks and gestures outside the dialog box will be ignored
    'width' is the width of the dialog
    'height' if supplied will override the sizes calculated by the browser
*/

function dialogBox(theId, width, height, modal) {

    if(currentDialogBoxId) { dialogBoxClose(currentDialogBoxId); }

    currentDialogBoxId = theId;

    if(modal) {
        document.body.style.overflow = 'hidden'; // disable all scrolling while in modal dialog
        if(document.body.addEventListener) {
            document.body.addEventListener('touchmove', iOSDisableScroll, false); // disable all move gestures in iOS
        }
    }

    var pageWidth = $(document).width();
    var pageHeight = $(document).height();
    var viewportWidth = $(window).width();
    var viewportHeight = $(window).height();
    var scrollTop = $(window).scrollTop();
    var scrollLeft = $(window).scrollLeft();
    
    // var viewport_dimensions    = document.viewport.getDimensions();
    // var viewport_scroll_offset = document.viewport.getScrollOffsets();

    if(modal) {
        var bg = document.createElement('div'); 
        bg.setAttribute('id',theId + '_bg');
        bg.style.display = 'none';
        document.body.appendChild(bg);
        bg.style.position = 'absolute';
        bg.style.backgroundColor = '#000000';
        bg.style.opacity = .50;
        bg.style.filter = 'alpha(opacity=50)';
        bg.style.top = scrollTop + "px";
        bg.style.height = viewportHeight + "px";
        bg.style.left = scrollLeft + "px";
        bg.style.width = viewportWidth + "px";
        bg.style.zIndex = 99;
        bg.style.display = "";

    }
    
    var dialog = document.getElementById(theId);
    
    dialog.style.position = 'absolute';

    dialog.style.zIndex  = 100; // position above background if modal
    
    dialog.style.width    = width + "px";

    if(height) {
        dialog.style.height    = height + "px";
    }
    
    dialog.style.left = ((viewportWidth - width)/2 + scrollLeft) + "px";    

    if(navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPod/i) || navigator.userAgent.match(/iPad/i)) {
        dialog.style.position = 'absolute';
        dialog.style.top = (scrollTop + 30) + "px";
    }
    else {
        dialog.style.position = 'fixed';
        dialog.style.top = "50px";
    }
    
    dialogBoxListenForResizeAndScroll(); // if the user resizes (or re-orients on iOS) we will need to recalculate position
    
    dialog.style.display = ''; // reveal it
    
    return dialog;
}

/* close the dialog box */

function dialogBoxClose() {
    if(currentDialogBoxId) {
        var dialog = document.getElementById(currentDialogBoxId);
        if(dialog) {
            dialogBoxStopListeningForResizeAndScroll();
            
            dialog.style.display = 'none'; // hide it
            
            // if it is modal remove the background
            var backgroundNode = document.getElementById(currentDialogBoxId + '_bg');
            if(backgroundNode) {
                backgroundNode.style.display = "none";
                backgroundNode.parentNode.removeChild(backgroundNode);
                
                document.body.style.overflow = ''; // re-enable scrolling
                if(document.body.removeEventListener) {
                    document.body.removeEventListener('touchmove', iOSDisableScroll, false); // re-anable touch gestures in iOS
                }
            }
            
            currentDialogBoxId = '';
            
            if(dialogCloseDestination) {
            	document.location.href = dialogCloseDestination;
            }
        }
        else {
            alert('could not close ' + currentDialogBoxId);
        }
    }
}

function dialogSetCloseDestination(path) {
	dialogCloseDestination = path;
}

/* called if the window changes size or the document scrolls */

function dialogBoxHandleResizeOrScroll() {
    if(currentDialogBoxId) {        
        var dialog = document.getElementById(currentDialogBoxId);
        if(dialog) {
            var pageWidth = $(document).width();
            var pageHeight = $(document).height();
            var viewportWidth = $(window).width();
            var viewportHeight = $(window).height();
            var scrollTop = $(window).scrollTop();
            var scrollLeft = $(window).scrollLeft();

            // var viewport_dimensions    = document.viewport.getDimensions();
            // var viewport_scroll_offset = document.viewport.getScrollOffsets();

            if(dialog.style.position == 'absolute') {
                dialog.style.top = (scrollTop + 30) + "px";
            }
            dialog.style.left = ((viewportWidth - parseInt(dialog.style.width))/2 + scrollLeft) + "px";
            var bg = document.getElementById(currentDialogBoxId + '_bg');
            if(bg) {
                bg.style.top = scrollTop + "px";
                bg.style.height = viewportHeight + "px";
                bg.style.left = scrollLeft + "px";
                bg.style.width = viewportWidth + "px";
            }
        }
    }
}

function dialogBoxListenForResizeAndScroll() {
    $(window).bind("resize", dialogBoxHandleResizeOrScroll);
    $(window).bind("scroll", dialogBoxHandleResizeOrScroll);
}

function dialogBoxStopListeningForResizeAndScroll() {    
    $(window).unbind("resize", dialogBoxHandleResizeOrScroll);
    $(window).unbind("scroll", dialogBoxHandleResizeOrScroll);
}

/* prevent gestures on the document */

function iOSDisableScroll(e){ e.preventDefault(); }

/* utilities */

function conditionalCookiePane(true_pane_name, false_pane_name, cookie_name) 
{
    var c = getCookie(cookie_name);
    var t = getPanesByName(true_pane_name);
    var f = getPanesByName(false_pane_name);
    if(c) {
        for(var i = 0; i < t.length; i++) {
            t[i].style.display = '';
        }
        for(var i = 0; i < f.length; i++) {
            f[i].style.display = 'none';
        }
    }
    else {
        for(var i = 0; i < f.length; i++) {
            f[i].style.display = '';
        }
        for(var i = 0; i < t.length; i++) {
            t[i].style.display = 'none';
        }
    }
}

function getXmlFirstChildData(tag,xmldoc) {

	var node = xmldoc.getElementsByTagName(tag).item(0);

	if(node && node.firstChild) { 
		return unescape(node.firstChild.data);
	}
	else {
		return "";
	}
}

function getPanesByName(name) 
{
    var objs = getElementsByName('span',name);
    return objs.concat(getElementsByName('div',name));
}

function getQueryStringParams() {
	var params = new Array;
	
	var queryString = String (document.location).split ('?')[1];
	if (!queryString) return false;
	
	var pairs = queryString.split('&');
	
	for (var i = 0 ; i < pairs.length; i++) {
		var kv = pairs[i].split('=');
		params[kv[0]] = kv[1];
	}
	
	return params;
}

function getElementsByName(tag, name) 
{
     var objs = document.getElementsByTagName(tag);
     var found = new Array();
     for(i = 0; i < objs.length; i++) {
          if(objs[i].getAttribute("name") == name) {
               found[found.length] = objs[i];
          }
     }
     return found;
}



