function validateform(frmobject) {
    var temp = frmobject.serialize().split("&");
    for (i = 0; i < temp.length; i++) {
        var mystr = temp[i].split("=");
        if (mystr[0] != "address2") {
            if (mystr[1] == "") {
                alert("Please, fill the form");
                $(mystr[0]).focus();
                return false;
            }
        }
    }
    return true;
}

function generic(script, querystr, strloader, strdest) {
    var dest = (strdest != "") ? $(strdest) : $('res');
    if (strloader != " ") {
        var loader = (strloader != "") ? $(strloader) : $('loading');
        new Ajax.Updater(dest.id, script, {
            method: 'post',
            evalScripts: false,
            postBody: querystr,
            onCreate: $(loader).update("<span>Loading...</span>"),
            onFailure: function() {
                alert('');
                $(loader).update();
            },
            onComplete: function() {
                if (Ajax.activeRequestCount <= 1) $(loader).update();
            }
        });
    } else {
        new Ajax.Updater(dest.id, script, {
            method: 'post',
            evalScripts: false,
            postBody: querystr
        });
    }
/*
	try {
		_uacct = "UA-2980899-1";
		urchinTracker();
	} catch(err) {}
	*/
}

function errors(strdest, strmsg) {
    var div = document.createElement("div");
    div.setAttribute("class", "error");
    if (strmsg != "") {
        div.appendChild(document.createTextNode(strmsg));
    } else {
        div.appendChild(document.createTextNode("Error!!!"));
    }
    $(strdest).appendChild(div);
}

function __swafpos(myscript, myquerystring, myloader, mydest, p) {
    myquerystring += p;
    generic(myscript, myquerystring, myloader, mydest);
}

function validsearch(mode) {
    var id, Go = true;

    if (mode == 'search') id = 'searchBox';
    else id = 'fullsearchBox';

    if ($(id).value == 'Search...') {
        alert('Please, specify a term to search...');
        Go = false;
    }
    if ($(id).value.length < 2) {
        alert('Your search criteria must have at least 2 characters...');
        $(id).value = '';
        $(id).focus();
        Go = false;
    }
    return Go;
}

function validMail(strMail) {
    var reg2 = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?)$/;
    if (!reg2.test(strMail)) {
        alert("Invalid email address");
        return false;
    } else {
        return true;
    }
}

/**
 * POSTCARD GENERATOR / PROCESSOR
 * begin
 */
function darkScreen(vis, callback, options) { // Pass true to gray out screen, false to ungray
    var options = options || {};
    var zindex = options.zindex || 50;
    var opacity = options.opacity || 70;
    var opaque = (opacity / 100);
    var bgcolor = options.bgcolor || '#000000';
    var dark = document.getElementById('darkenScreenObject');
    if (vis) { // Calculate the page width and height 
        dark.style.opacity = 0;
        dark.style.MozOpacity = 0;
        dark.style.filter = 'alpha(opacity=' + opacity + ')';
        dark.style.zIndex = zindex;
        dark.style.backgroundColor = bgcolor;
        dark.style.width = j(window).width()+'px';
        dark.style.height = j(document).height()+'px';
        dark.style.display = 'block';
        j('#darkenScreenObject').fadeTo(500,opaque,callback);
    }else {
        dark.style.display = 'none';
    }
}
var pcardProcessor = window.location.protocol+"//"+window.location.host+"/includes/postcard_processor.php";
function resetPostcardForm(show,close,imgurl,id){
    if(close){
        document.forms['postcard'].reset();
        var btn = '<a href="javascript:void(j(\'#formContainer-'+id+'\').fadeIn());" style="font-weight:bolder"><img border="0" src="'+imgurl+'" /></a>';
        j('#formStatus'+id).html(btn);
    }else{
        j('#pcard_recip_name'+id).attr('value','');
        j('#pcard_recip_email'+id).attr('value','');
        j('#formStatus'+id).empty();
    }
    var ran = Math.floor(Math.random()*10000000);
    j('#pcard_seed'+id).attr('value', ran);
    j('#formPreview'+id).html('Click \'PREVIEW\' to see your postcard.');
    if(show){
        j('#formContainer-'+id).fadeIn();
    }else{
        j('#formContainer-'+id).fadeOut();
    }
}

function processPostcardForm(object,id){
    var o = object;
    j('#formContainer-'+id+' .postcard_field').each(function(){
        j(this).css({
            backgroundColor: '#c5c5c5',
            color: '#5A5A5A'
        });
    });
    j('#formStatus'+id).empty();
    if(typeof(o) == 'object'){
        if(o.hasOwnProperty('output')){
            darkScreen(true, function(){
                Dialog.create('pcard_preview','/includes/postcards/generated/'+o.valid.pcard_seed+'.html',
                {
                    width:640,
                    height:480,
                    title:'Postcard Preview',
                    closebutton:true
                });
                j('#pcard_preview_cont'+id).css({
                    overflow: '',
                    height: ''
                });
                var leftPosition = (j(document).width() - j('#pcard_preview'+id).width()) / 2;
                var posY = (document.documentElement.scrollTop) ? document.documentElement.scrollTop : window.scrollY;
                j('#pcard_preview'+id).css({
                    position: 'absolute',
                    left:leftPosition,
                    top:posY+10
                });
            }
            );
        }
        if(o.hasOwnProperty('invalid')){
            j('.postcard_field').each(function(el){
                j(this).css({
                    backgroundColor: '#c5c5c5',
                    color: '#5A5A5A'
                });
            });
            for(property in o.invalid){
                j('#'+property+id).css({
                    backgroundColor: '#3c3c3c',
                    color: '#fff'
                });
            }
            j('#formStatus'+id).innerHTML = 'Please, fix the highlighted fields.';
        }
        if(o.hasOwnProperty('valid')){
            for(property in o.valid){
                j('#'+property+id).css({
                    backgroundColor: '#c5c5c5',
                    color: '#5A5A5A'
                });
            }
        }
    }
}

function createPostcardForm(template,imgurl){
    var t = (typeof(template) != 'undefined') ? template : 1;
    var forward = (location.href.match(/forwardEvite$/i) != null) ? true : false;
    imgurl = (typeof(imgurl) != 'undefined') ? imgurl : 'http://www.perimeter.org/images/ministries/womenonwednesday/send_an_evite.jpg';
    var pcardBtn = '<img src="'+imgurl+'" border="0" />';
    var ran = Math.floor(Math.random()*10000000);
    if(typeof($) == 'undefined'){
        alert('The postcard form requires the Prototype library');
        return;
    }
    if(typeof(window.location.search) != 'undefined'){
        var arr = window.location.search.replace(/^\?/, '').split(/&/gi);
    }
    var id = Math.ceil(Math.random()*10000000000);
    document.write('<span id="formStatus'+id+'" style="text-align:center!important"><a href="javascript:void(document.getElementById(\'formContainer-'+id+'\').style.display = \'block\');" style="font-weight:bolder">'+pcardBtn+'</a></span>');
    document.write('<div id="formContainer-'+id+'" class="postcard" style="display:'+((forward)? 'block':'none' )+'">');
    document.write('<form onsubmit="javascript:return false;" action="'+pcardProcessor+'" method="post" id="postcard" name="postcard">');
    document.write('<input type="hidden" value="'+ran+'" id="pcard_seed" name="pcard_seed">');
    document.write('<table align="center" width="82%" style="margin:auto" class="postcardForm"><tbody>');
    document.write('<tr><td align="right" class="label" width="35%">Your email address:</td><td align="left"><input class="postcard_field" type="text"  id="pcard_sender_email'+id+'" name="pcard_sender_email"></td></tr>');
    document.write('<tr><td align="right" class="label" width="35%">Your name:</td><td align="left"><input class="postcard_field" type="text"  id="pcard_sender_name'+id+'" name="pcard_sender_name"></td></tr>');
    document.write('<tr><td align="right" class="label" width="35%">Recipient\'s email address:</td><td align="left"><input class="postcard_field" type="text"  id="pcard_recip_email'+id+'" name="pcard_recip_email"></td></tr>');
    document.write('<tr><td align="right" class="label" width="35%">Recipient\'s name:</td><td align="left"><input class="postcard_field" type="text"  id="pcard_recip_name'+id+'" name="pcard_recip_name"></td></tr>');
    document.write('<tr><td align="right" class="label" width="35%">Subject:</td><td align="left"><input class="postcard_field" type="text"  id="pcard_subject'+id+'" name="pcard_subject"></td></tr>');
    document.write('<tr><td align="right" class="label" width="35%" valign="top">Message:</td><td align="left"><textarea class="postcard_field" rows="4" cols="38" id="pcard_message'+id+'" name="pcard_message"></textarea></td></tr>');
    document.write('<tr><td></td><td align="center" style="text-align:center!important;padding-right:45px"><input class="pcard_btn" value="false" type="image" src="/images/btn_send.jpg" id="postcard_send'+id+'" name="postcard_send"'+
        'onclick="javascript:void(sendPostcardData(true,'+t+',\''+imgurl+'\',\''+id+'\'));">'+
        '&nbsp;<input class="pcard_btn" value="false" type="image" src="/images/btn_preview.jpg" name="postcard_preview" id="postcard_preview'+id+'" onclick="javascript:void(sendPostcardData(false,'+t+',\''+imgurl+'\',\''+id+'\'));"></td></tr>');
    document.write('</tbody></table></form>');
    document.write('<div id="formPreview'+id+'" style="font-weight:bold!important;font-size:10px!important;">Click \'PREVIEW\' to see your postcard.</div>');
    document.write('</div>');
}

function sendPostcardData(deliver, template,imgurl,id){
    j('.pcard_btn').each(function(){
        j(this).attr('value',false);
    });
    if(deliver == true){
        j('#postcard_send'+id).attr('value',true);
        j('#postcard_preview'+id).attr('value',false);
    }else{
        j('#postcard_send'+id).attr('value',false);
        j('#postcard_preview'+id).attr('value',true);
    }
    // build data
    var out = '';
    out += 'pcard_sender_email='+escape(j('#pcard_sender_email'+id).attr('value'));
    out += '&pcard_sender_name='+escape(j('#pcard_sender_name'+id).attr('value'));
    out += '&pcard_recip_email='+escape(j('#pcard_recip_email'+id).attr('value'));
    out += '&pcard_recip_name='+escape(j('#pcard_recip_name'+id).attr('value'));
    out += '&pcard_subject='+escape(j('#pcard_subject'+id).attr('value'));
    out += '&pcard_message='+escape(j('#pcard_message'+id).attr('value'));
    out += '&pcard_seed='+escape(j('#pcard_seed'+id).attr('value'));
    out += '&postcard_preview='+escape(j('#postcard_preview'+id).attr('value'));
    out += '&postcard_send='+escape(j('#postcard_send'+id).attr('value'));
    out += '&template='+template;
    j.ajax({
        url: pcardProcessor,
        cache: false,
        type: 'POST',
        data: out,
        dataType: 'json',
        success: function(data){
            if(data == 'processed'){
                j('.postcard_field').each(function(){
                    j(this).css({
                        backgroundColor: '#c5c5c5',
                        color: '#5A5A5A'
                    });
                });
                var done = 'The postcard was sent successfully. It should arrive in a couple of minutes.';
                j('#formStatus'+id).html(done + '<br /><a href=javascript:void(resetPostcardForm(true,false,\''+imgurl+'\',\''+id+'\'))>Send another</a>&nbsp;-&nbsp;<a href=javascript:void(resetPostcardForm(false,true,\''+imgurl+'\',\''+id+'\'))>Close</a>');
            }else{
                processPostcardForm(data,id);
            }
        }
    });
    return false;
}
/**
 * POSTCARD GENERATOR / PROCESSOR
 * end
 */
function loadJs(url)
{
    var path = 'http://'+location.host+'/'+url;
    var e = document.createElement('script');
    e.src = url;
    e.type='text/javascript';
    document.getElementsByTagName('head')[0].appendChild(e);
}

function checkJs(js){
    var scripts = document.getElementsByTagName('script');
    var re = new RegExp(js+'.js$', 'gi');
    var ret = false;
    for(s in scripts){
        if(typeof(scripts[s].src) != 'undefined'){
            if(scripts[s].src.match(re)){
                ret = true;
                break;
            }else{
                ret = false;
            }
        }
    }
    return ret;
}


function navigateParagraphs(nav){
//    j(nav+' p').each(function(n,el){
//        if(typeof(j(el)[0].childNodes) != 'undefined'){
//            var arr = j(el)[0].childNodes;
//            var url = 'void(0)';
//            for(x in arr){
//                if(typeof(arr[x].href) != 'undefined'){
//                    var p = j(el);
//                    var blank = (arr[x].target.match(/_blank/gi)) ? true : false;
//                    url = arr[x].href;
//                    arr[x].href = 'javascript:void(0)';
//                    arr[x].target = '_self';
//                    p.bind('click', function(){
//                        if(!blank){
//                            location.href = url;
//                        }else{
//                            window.open(url);
//                        }
//                    });
//                    var purl = (url.match(/\?/g)) ? '?'+url.replace(/^[^\?]+\?(.*)$/gi,'$1') : url.replace(/http:\/\/[^\/]+\/(.*)$/gi,'$1');
//                    var curl = (location.search != '') ? location.search : location.pathname;
//                    if(purl == curl){
//                        var newh = p.html().replace(/<a([^>]+)>/gi,'<a$1 style="font-weight:bolder;">');
//                        p.html(newh);
//                    }
//                }
//            }
//        }
//    });
}
