//var jQ = jQuery.noConflict();
var Y=YAHOO;
PF.Dom=Y.util.Dom;
PF.requesttime=0;
PF.versiontime=0;

PF.trim=function(str) {return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');}

PF.getSelection=function() {
 var txt = '';
 if (document.getSelection)
 {
 txt = document.getSelection();
 }
 else if (document.selection)
 {
 txt = document.selection.createRange().text;
 }
 else if (window.getSelection)
 {
 txt = window.getSelection();
 }
 return(''+txt);
};

PF.handleSelect=function(e) {
 var txt=PF.getSelection();
 txt=PF.trim(txt);
 //var qbox = Y.util.Dom.get('qbox');
 //var query=qbox.value;
 //qbox.value=qbox.value+' \"'+txt+'\"'
 if (txt!='') PF.add(txt,true,PF.context_id,PF.topichash,0)
// PF.add(txt,true,PF.context_id,PF.topichash,0)
}
if (PF.page=="discover") {
    var el=YAHOO.util.Dom.get('thetext')
    // var el=document.body;
    YAHOO.util.Event.addListener(el,"mouseup",PF.handleSelect)
    var el=YAHOO.util.Dom.get('')
};

//PF.async=Y.util.Connect.asyncRequest; ///shortcutting this way FAILS
PF.activate=function(id) {
    var item=PF.Dom.get(id);
    PF.Dom.replaceClass(item,'hidden','visible');
    };
PF.deactivate=function(id) {
    var item=PF.Dom.get(id);
    PF.Dom.replaceClass(item,'visible','hidden')
    };
PF.showmenu=function(menuid,actionlist) {
    if (Y.lang.isUndefined(PF.menu[menuid])) {
      PF.menu[menuid] = new Y.widget.Menu(menuid, {"context": ["menub-"+menuid, "tl", "br"]});
      PF.menu[menuid].addItems(actionlist);
      PF.menu[menuid].render(document.body);
      }
    PF.menu[menuid].show();
    PF.log('showing');
    }
Y.widget.Logger.enableBrowserConsole();
PF.log=Y.log;
PF.menu={};
PF.toggle=function(id) {
	if (PF.Dom.hasClass(id,'hidden')) {
		PF.Dom.removeClass(id,'hidden')
		} else {
		PF.Dom.addClass(id,'hidden')
		};
	};
PF.show=function(id) {
	if (PF.Dom.hasClass(id,'hidden')) {
		PF.Dom.removeClass(id,'hidden')
		};
	};
PF.hide=function(id) {
	PF.Dom.addClass(id,'hidden')
	};

PF.initializeSelection=function() {
 PF.processSelection(1);
}
PF.refreshSelection=function() {
 PF.processSelection(0);
}
PF.processSelection=function(initialize) {
 var qbox = Y.util.Dom.get('qbox');
 var query=qbox.value;
 for (cat in PF.phrases) {
   var phrases=PF.phrases[cat];
   var phix, ph;
   for (phix in phrases) {
	ph=phrases[phix];
	// http://simonwillison.net/2006/Jan/20/escape/
    	phr= ph.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
	var s=new RegExp('\"'+phr+'\"')
	var id='ph_'+escape(cat)+'_'+escape(ph);
	button = Y.util.Dom.get(id);
	if (Y.lang.isNull(button)) {
	  PF.log(id);
	} else {
           if (query.search(s)>=0) {
		// PF.Dom.addClass(id,'selected');
		button.checked = true;
		} else {
	          button.checked = false;
		}
        }
	if (initialize==1) { YAHOO.util.Event.addListener(id, 'click', PF.handlePhrase); }
	}
   }
 }

PF.handlePhrase=function(e) {
	var targ;
	if ('target' in e) targ=e.target; else targ=e.srcElement;
	var str=targ.id;
	str=str.replace(/^ph_[^_]+_/,'');
	var term=unescape(str);
	var flag=0;
	if (e.shiftKey) flag=1;
	if (e.ctrlKey) flag=2;
	// PF.add(term, PF.notIphone, PF.context_id, PF.topichash,flag);
	PF.add(term, true, PF.context_id, PF.topichash,flag);
	return(true);
}

if (!Y.lang.isUndefined(PF.phrases)) YAHOO.util.Event.onDOMReady(PF.initializeSelection);
PF.fill_in_results=function() { //@@
 if (!Y.lang.isUndefined(PF.jsearches) && !PF.jsearchpending) { 
   PF.jsearchpending=true;
   if (PF.jsearches.length>=1) {
    var a=PF.jsearches.pop();
    var url=a[1];
    var srid='searchResults_'+a[0];
    var onFailure=function(o) {
      PF.log('connection failure at '+o.argument.url); 
      PF.jsearches.push(o.argument.a);
      PF.jsearchpending=false;
      PF.handleScroll();
      };
    var callback={
     success: function(o) {
      if (o.responseText==='unrecognized') onFailure(o); else {
         //True success
         PF.log('server response= ...');
 	var sr=Y.util.Dom.get(o.argument.srid)
 	//sr.innerHTML='<div style="height:300px; width:600px; overflow: auto">'+o.responseText+'</div>'
 	sr.innerHTML=o.responseText
	PF.jsearchpending=false;
	//@@ queue the next.
	PF.handleScroll();
	return false;
 	}
       },
     failure: onFailure,
     timeout: 600000, //timeout in milliseconds
     argument: {url: url, srid: srid, a:a}
     };
    var transaction=Y.util.Connect.asyncRequest('GET',url, callback, null);
    }
 }}

PF.handleScroll= function(){
       var Ydom = YAHOO.util.Dom;
       if (!Y.lang.isUndefined(PF.jsearches) && PF.jsearches.length>=1) {
	       var next=PF.jsearches.pop();PF.jsearches.push(next); //peek
	       var bot = Ydom.getDocumentScrollTop()+Ydom.getViewportHeight();
	       var r=Ydom.get('searchResults_'+next[0]);
	       if (r.offsetTop<=(bot+100)) {PF.fill_in_results();}
	      }
	return false;
	};
YAHOO.util.Event.onDOMReady(PF.fill_in_results);
YAHOO.util.Event.addListener(window, 'scroll', PF.handleScroll);

PF.add=function(query, refresh, context_id, topichash, flag) {
 var qbox = Y.util.Dom.get('qbox');
 var qformat;
 //if (query.search(/ /) >= 0) {
 //  qformat='\"'+query+'\"'
 //} else {
 //  qformat=query
 //}
 if (query == '') {
    qbox.value='';
    PF.show('likes');
    PF.hide('searchresults');
 }
 else{ 
  PF.hide('likes');
  PF.show('searchresults');
 var baseformat='\"'+query+'\"'
 if (flag==2) {
	 qformat='-\"'+query+'\"'
	} else if (flag==1) {
	 qformat='OR \"'+query+'\"'
	} else { //default
	 qformat=baseformat
	}
 var myreg = new RegExp('\\s*(-)?(OR )?'+baseformat,'g');
 if (qbox.value.search(myreg) >= 0) {
    qbox.value=qbox.value.replace(myreg,'');
 } else {
    if (qbox.value=='') {
	qbox.value=qformat;
	} else {
	 qbox.value=qbox.value+' '+qformat;
	}
   }
 }
 //window.location applied to this redirects. Probably using the YUI history manager we can achieve a URL shift without a refresh.
 //(PF.selfURL + "?" + "context_id=" + escape(context_id) + "&topichash=" + escape(topichash) + "&query=" + escape(qbox.value));

 PF.refreshSelection()
 if (refresh == 1) { PF.ajaxSearchRefresh(context_id, topichash) }
 return false;
}

PF.ajaxSearchRefresh=function(context_id, topichash) {
 if (PF.localAjax) {PF.localSearchRefresh(context_id, topichash);}
 else {PF.iframeSearchRefresh(context_id, topichash);}
}

PF.iframeSearchRefresh=function(content_id, topichash) {
 var sr=Y.util.Dom.get('searchResults')
 var qbox = Y.util.Dom.get('qbox');
 var head='<style type="text/css"><!-- .iframe_body {height: 100%; width: 100%; margin: 0; overflow: hidden; padding: 0;}#content_iframe {height: 100%; width: 100%; margin: 0; overflow: hidden; padding: 0;} --></style>\n';
 var body='<iframe id=\"content_iframe\" frameborder=\"0\" scrolling=\"auto\" src=\"http://www.google.com/search?q=';
 var q=escape(qbox.value);
 //var features='&tbs=qdr:w,whnv:1'
 var features='&tbs=qdr:y'
 // var features='&'
 var tail='\"><a href=\"@@\">Click to view content</a><br>(your browser does not support iframe\'s)<br></iframe>';
 sr.innerHTML=head+body+q+features+tail;
}

PF.localSearchRefresh=function(context_id, topichash) {   
 var sr=Y.util.Dom.get('searchResults')
 var qbox = Y.util.Dom.get('qbox');
 sr.innerHTML="<img src='/img/loading.gif' /> Results for "+qbox.value+" are loading";
 var url=PF.searchURL + "?" + "context_id=" + escape(context_id) + "&topichash=" + escape(topichash) + "&query=" + escape(qbox.value)

 var onFailure=function(o) {
     PF.log('connection failure at '+o.argument.url); 
     };
 var callback={
   success: function(o) {
     if (o.responseText==='unrecognized') onFailure(o); else {
        //True success
        PF.log('server response='+o.responseText);
	var versiontime=o.argument.versiontime
	var sr=Y.util.Dom.get('searchResults')
	if (versiontime > PF.versiontime) {
		var sr=Y.util.Dom.get('searchResults')
		sr.innerHTML=o.responseText
		// sr.innerHTML=versiontime+' '+o.responseText
		sr.innerHTML=o.responseText
		PF.versiontime=versiontime
		} else {
	  PF.log('skipping deprecated')
	}
	}
      },
    failure: onFailure,
    timeout: 600000, //timeout in milliseconds
    argument: {url: url, versiontime: PF.requesttime+1}
    };
  PF.requesttime=PF.requesttime+1
  var transaction=Y.util.Connect.asyncRequest('GET',url, callback, null);
}

PF.button_states=['filled', 'refill', 'selected','deselected','loading','read', 'unread','add','disable','starred','unstarred','present','delete', 'negative-phrase', 'delete-phrase', 'add-phrase', 'disable-phrase', 'disable-phrase-subscription', 'add-phrase-subscription']
PF.updateStar=function(id,bclass,status) {
 for (var ix in PF.button_states) {
  var stat=PF.button_states[ix]
  var b=bclass+'-'+stat+'-'+id
  if (stat===status) {PF.Dom.removeClass(b,'hidden')} else {PF.Dom.addClass(b,'hidden')};
  }
};
PF.star=function(id,status,bclass,it,doconfirm,followup) {
 if (doconfirm) {
	var handleYes = function() {
		PF.star(id,status,bclass,it,false,followup);
		this.hide();
	};
	var handleNo = function() {
		this.hide();
	};

	PF.diag1=new YAHOO.widget.SimpleDialog("diag1", 
			 { width: "140px",
			   fixedcenter: true,
			   visible: true,
			   draggable: false,
			   close: false,
			   text: "Remove for sure?",
			   //icon: YAHOO.widget.SimpleDialog.ICON_HELP,
			   constraintoviewport: true,
			   buttons: [ { text:"Yes", handler:handleYes, isDefault:true },
						  { text:"No",  handler:handleNo } ]
			 } );
	PF.diag1.render(document.body); 
	PF.diag1.show()
	PF.log('here')
	return;
 };
 // handle doconfirm popup
 PF.updateStar(id,bclass,'loading');
 var a1=it; // PF.Dom.getAncestorByTagName(it,'a');
 PF.log(a1);
 var url=a1.href+'&ajax=1'

 PF.log('Notifying server with: '+url);
 var onFailure=function(o) {
     PF.log('connection failure at '+o.argument.url); 
     PF.log(o);
     //signal for reload of whole page to guarantee up to date status
     alert('Connection to server timed out. Refreshing')
     window.location.reload(true);
     };
 var callback={
   success: function(o) {
     if (o.responseText==='unrecognized') onFailure(o); else {
        //True success
        PF.log('server response='+o.responseText);
	if (o.argument.followup==='follow') {
	        PF.updateStar(o.argument.id,o.argument.bclass,o.argument.status); //pull it from argument, could perhaps better pull it from the server response using:
	};
	if (o.argument.followup==='delete') {
	  var li='li'+'-'+id // refers to the entire li
	  PF.Dom.addClass(li,'hidden');
	};
	var resp=Y.lang.JSON.parse(o.responseText);
	PF.log(resp);
	}
      },
    failure: onFailure,
    timeout: 600000, //timeout in milliseconds
    argument: {url: url, a1: a1, id: id, status:status, followup:followup, bclass:bclass}
    };
  //var transaction=PF.async('GET',url, callback, null); // this line is broken
  var transaction=Y.util.Connect.asyncRequest('GET',url, callback, null);
  PF.log(transaction)
};


if (!Y.lang.isUndefined(YAHOO.util.DDProxy)) {
//draggables
PF.DDObject = function(id, sGroup, config) {
    PF.DDObject.superclass.constructor.apply(this, arguments);
    this.initPlayer(id, sGroup, config);
};

YAHOO.extend(PF.DDObject, YAHOO.util.DDProxy, {

    TYPE: "DDObject",

    initPlayer: function(id, sGroup, config) {
        if (!id) { 
            return; 
        }

        var el = this.getDragEl()
        YAHOO.util.Dom.setStyle(el, "borderColor", "transparent");
        YAHOO.util.Dom.setStyle(el, "opacity", 0.76);

	if (config == "is target") {
          this.isTarget = true;
	}
  	else {
 	  this.isTarget = false;
	}

        this.originalStyles = [];

        this.type = PF.DDObject.TYPE;
        this.slot = null;

        this.startPos = YAHOO.util.Dom.getXY( this.getEl() );
        YAHOO.log(id + " startpos: " + this.startPos, "info", "example");
    },

    startDrag: function(x, y) {
        YAHOO.log(this.id + " startDrag", "info", "example");
        var Dom = YAHOO.util.Dom;

        var dragEl = this.getDragEl();
        var clickEl = this.getEl();

        dragEl.innerHTML = clickEl.innerHTML;
        dragEl.className = clickEl.className;

        //Dom.setStyle(dragEl, "color",  Dom.getStyle(clickEl, "color"));
        //Dom.setStyle(dragEl, "backgroundColor", Dom.getStyle(clickEl, "backgroundColor"));
	Dom.setStyle(dragEl, "border", "2px solid blue");

        Dom.setStyle(clickEl, "opacity", 0.1);

	if (0) {
        var targets = YAHOO.util.DDM.getRelated(this, true);
        YAHOO.log(targets.length + " targets", "info", "example");
        for (var i=0; i<targets.length; i++) {
            
            var targetEl = this.getTargetDomRef(targets[i]);

            if (!this.originalStyles[targetEl.id]) {
                this.originalStyles[targetEl.id] = targetEl.className;
            }

            targetEl.className = "target";
        }
	}
    },

    getTargetDomRef: function(oDD) {
        if (oDD.player) {
            return oDD.player.getEl();
        } else {
            return oDD.getEl();
        }
    },

    endDrag: function(e) {
	if (!Y.lang.isUndefined(PF.last_el)) { // clear old style
		YAHOO.util.Dom.setStyle(PF.last_el, "border", "");
		}

        // reset the linked element styles
        YAHOO.util.Dom.setStyle(this.getEl(), "opacity", 1);

        // this.resetTargets();
    },

    resetTargets: function() {

        // reset the target styles
        var targets = YAHOO.util.DDM.getRelated(this, true);
        for (var i=0; i<targets.length; i++) {
            var targetEl = this.getTargetDomRef(targets[i]);
            var oldStyle = this.originalStyles[targetEl.id];
            if (oldStyle) {
                targetEl.className = oldStyle;
            }
        }
    },

    onDragDrop: function(e, id) {
        // get the drag and drop object that was targeted
        var oDD;
        
        if ("string" == typeof id) {
            oDD = YAHOO.util.DDM.getDDById(id);
        } else {
            oDD = YAHOO.util.DDM.getBestMatch(id);
        }

        var el = this.getEl();

	// alert('Copy '+el.id+' into '+oDD.id);
        if (1) {
        // PF.Dom.removeClass(oDD.id,'hidden');
	var topicid = oDD.id;
	topicblockid = topicid.replace(/li-/, "topicblock-");
	topicloadingid = topicid.replace(/li-/, "topicloading-");
	topichash = topicid.replace(/li-/, "");
	var source = el.id;
        source = source.replace(/searchresult-/, "");
        source = source.replace(/li-/, "");
        // PF.Dom.addClass(topicblockid,'hidden');
        // PF.Dom.removeClass(topicloadingid,'hidden');

	if (1){ 
        var onFailure=function(o) {
          PF.log('connection failure at '+o.argument.topicblockid);
          PF.log(o);
          alert('Connection to server timed out. Refreshing')
          window.location.reload(true);
        };

        var callback={
          success: function(o) {
            if (o.responseText==='unrecognized') onFailure(o); else {
             PF.log('server response= ...');
             PF.Dom.removeClass(o.argument.topicblockid,'hidden');
             PF.Dom.addClass(o.argument.topicloadingid,'hidden');
	     window.location.reload(true);
	     return false;
 	    }
          },
          failure: onFailure,
          timeout: 600000, //timeout in milliseconds
          argument: {topicblockid: topicblockid, topicloadingid: topicloadingid}
        };
	}
	var submittotopic = PF.submittotopic + '?topichash=' + oDD.id + '&submission=' + el.id + '&ajax=1';
        var handleYes = function() {
                // PF.star(id,status,bclass,it,false,followup);
                PF.Dom.addClass(topicblockid,'hidden');
                PF.Dom.removeClass(topicloadingid,'hidden');
		if (el.id.match(/^li-/)) { 
	          PF.Dom.addClass(el.id,'hidden');
		}
		Y.util.Connect.asyncRequest('GET',submittotopic,callback, null)
                this.hide();
        };
        var handleNo = function() {
                this.hide();
        };

        PF.diag1=new YAHOO.widget.SimpleDialog("diag1",
                         { width: "140px",
                           fixedcenter: true,
                           visible: true,
                           draggable: false,
                           close: false,
                           text: "Add " + unescape(source) + " to " + unescape(topichash),
                           //icon: YAHOO.widget.SimpleDialog.ICON_HELP,
                           constraintoviewport: true,
                           buttons: [ { text:"Yes", handler:handleYes, isDefault:true },
                                                  { text:"No",  handler:handleNo } ]
                         } );
        PF.diag1.render(document.body);
        PF.diag1.show()
        PF.log('here')
	}

    },

    swap: function(el1, el2) {
        var Dom = YAHOO.util.Dom;
        var pos1 = Dom.getXY(el1);
        var pos2 = Dom.getXY(el2);
        Dom.setXY(el1, pos2);
        Dom.setXY(el2, pos1);
    },

    onDragOver: function(e, id) {
        var oDD;
        
        if ("string" == typeof id) {
            oDD = YAHOO.util.DDM.getDDById(id);
        } else {
            oDD = YAHOO.util.DDM.getBestMatch(id);
        }
	var el=oDD.getEl();
	if (!Y.lang.isUndefined(PF.last_el) && el!=PF.last_el) { // clear old style
		YAHOO.util.Dom.setStyle(PF.last_el, "border", "");
		}
	YAHOO.util.Dom.setStyle(el, "border", "2px solid red");
	PF.last_el=el; //store it globally.
    },

    onDrag: function(e, id) {
	if (!Y.lang.isUndefined(PF.last_el)) { // clear old style
		YAHOO.util.Dom.setStyle(PF.last_el, "border", "");
		}
    }

});
//end draggables
};

PF.bindHandlers=function() {
  var elements = YAHOO.util.Dom.getElementsByClassName('confirmSubmit', 'input');
  var eix;
  for (eix in elements) {
	var a=elements[eix];
	PF.log(a);
	var fnCallback=function(a){return function(e) {
	   PF.log(e)
	   YAHOO.util.Event.preventDefault(e);
	   var diag=new YAHOO.widget.SimpleDialog("diag2", 
			 { width: "140px",
//			   fixedcenter: true,
		           context: [a,'tl','br'],
			   visible: true,
			   draggable: false,
			   close: false,
			   text: "Remove for sure?",
			   constraintoviewport: true,
			   buttons: [ 
	{ text:"Yes", handler:function(){
		var f=a.form;PF.log(f);
		PF.tmp=f;
		//f.submit(); // Somehow it's not getting the right form data. In partciular the right likedirection
		this.hide();
		}, isDefault:true },
				      { text:"No",  handler:function(){this.hide();} } ]
			 } );
	    diag.render(document.body); 
	    diag.show();
	}}(a); //complete closure.

	YAHOO.util.Event.addListener(a, "click", fnCallback);
  }
}
YAHOO.util.Event.onDOMReady(PF.bindHandlers);
