var ip = new iphone();

checkCsoFragment();

var ti;
var editmode = false;
var onetapTot = 0;
var onetapOff = 0;
var onetapLim = 0;
var desktop = false;


window.onload = function() { 

    ip.setHandlers();

    setTimeout( home, 100);
    if ( $("searchterm") ) {
    	$("searchterm").focus();
    }
};


function checkCsoFragment() {

	var curr = window.location.toString();
	if ( curr.match(/#/) ) {
		
		var parts = curr.split("#");
		if ( parts.length > 1 && parts[1] != "" ) {
			 var comps = parts[1].split("&");
			 if ( comps.length > 1 ) {
				 var locn = "/a/cso?ci=" + comps[0] + "&t=" + comps[1];
				 window.location = locn;	 
			 }
		}
	}
}


function iphone() {
    this.decelScroll = new Array( 200, 185, 172, 159, 146, 134, 122, 111, 101, 91, 81, 72, 63, 55, 48, 41, 35, 29, 23, 18, 14, 10, 7, 4, 2, 1 );
    this.desktop = false;

	// var e = document.getElementById("tbox");
	// e.addEventListener( "focus", iphone.scrollIt, false );
    // iPhone blats the searchAgain form if it's at the bottom, so we add an
	// empty
    // div to the bottom of the page with enough height so that we can
	// auto-scroll
    // the page out of the way when the user clicks into the form
	// newel = document.createElement("div");
	// newel.style.height = "160px";
	// newel.style.id = "newel";
	// document.body.appendChild( newel );
    // window.scrollTo( 0, 1 );
    
    
} 



iphone.prototype.setHandlers = function() {

    // set up event listeners...
    

    try { 
        // used on results page for "more filters" link
        //$("filter4").addEventListener("click", this.moreFilters, false );
    }
    catch (e) {}

    try { 
        // used on results page for "more filters" link
        $("resultsLink").addEventListener("click", this.closeCsoPane, false );
    }
    catch (e) {}

}


iphone.prototype.chartExtender = function( csoid ) {
	
	var url = "/a/ajax?ajax=morechartentries&cho=" + ( chartLim + chartOff ) + "&chw=" + chartWeek + "&cid=" + encodeURIComponent(csoid);
	url = patchUrl( url );
	chartOff += chartLim;
	$("moreEntries").style.display = "none";
	$("moreEntriesSpinner").style.display = "block";
	func = function() {
		var el = document.createElement( "div");
		el.innerHTML = status;
		$("chartExtender").appendChild( el );
		$("moreEntriesSpinner").style.display = "none";
		if ( chartOff + chartLim < chartLen ) {
			$("moreEntries").style.display = "block";
		}

	}
	doAjax( url, func );
}

iphone.prototype.stackExtender = function( term ) {
	
	var url = "/a/ajax?ajax=morestackentries&o=" + ( stackLim + stackOff ) + "&t=" + encodeURIComponent( term );
	url = patchUrl( url );
	stackOff += stackLim;
	$("moreEntries").style.display = "none";
	$("moreEntriesSpinner").style.display = "block";
	func = function() {
		var el = document.createElement( "div");
		el.innerHTML = status;
		$("stackExtender").appendChild( el );
		$("moreEntriesSpinner").style.display = "none";
		if ( stackOff + stackLim < stackLen ) {
			$("moreEntries").style.display = "block";
		}

	}
	doAjax( url, func );
}



// generic list extender (i.e. "10 more friends"
iphone.prototype.listExtender = function( listname, target ) {

	
	if ( listname == "feedback" ) {
		tot = fbpage;
		fbpage += 1;
		url = "/a/ajax?ajax=morefeedback&sgp=" + encodeURIComponent( fbpage );
		url = patchUrl(url);
		$("moreFeedback").style.display = "none";
		$("spinner-feedback").style.display = "block";
		
		func = function() {
			if ( fbpage < fbtotal/10 ) {
				$("moreFeedback").style.display = "block";
			}
			$("spinner-feedback").style.display = "none";	
			var el = document.createElement( "div");
			el.innerHTML = status;
			$(target).appendChild( el );
			processEmbedders();
		}
	}
	
	doAjax( url, func );
}

// get more results - needs to manage multiple simultaneous lists for different sets of types, so is more
// complex than the above simple listExtender method
iphone.prototype.getMoreResults = function( type ) {

	var atype = type;
	if ( type == "")
		atype = "mixed";
	// handle the AJAX request for more results
	
//	var oterm="${params.ot?url!''}";
//	var tf="${params.tf?url!''}"; 
//	var tfv="${params.tfv?url!''}";
//	var nc="${params.nc?url!''}";
	
    var tot = $("total-" + atype).value;
    var off = parseInt( $("offset-" + atype).value ) + parseInt( (limit[atype]||10) );
    lim = limit[atype]||10;
    t   = term;
    ty  = type;
    url = "/a/ajax?ajax=moreresults&o=" + encodeURIComponent( off ) + "&l=" + encodeURIComponent( lim ) + "&ty=" + encodeURIComponent( ty );
    if ( window.location.toString().match(/sstoff=1/ ) ) {
    	url += "&sstoff=1&sstog=1";
    }
    url = patchUrl(url);
    
    // add feedstory-specific params, if present
    if ( oterm != "" ) { url = url + "&ot=" + oterm; }
    if ( tf != "" ) { url = url + "&tf=" + tf; }
    if ( tfv != "" ) { url = url + "&tfv=" + tfv; }
    if ( nc != "" ) { url = url + "&nc=" + nc; }
    
    
    func = function() { compMoreResults( type ); } ;
    $("spinner-" + type ).style.display="block";
    $("moreResults-" + type ).style.display="none";
    $("offset-" + atype).value = off;
    doAjax( url, func );
}


iphone.prototype.getMoreImageResults = function() {
    // handle the AJAX request for more image results
    off = ioffset + origilimit; // these vars are set as globals by results.ftl
    tot = itotal;
    lim = origilimit;
    t   = term;
    if ( t == "" ) { t = oterm; };
    ty  = type;
    url = "/a/ajax?ajax=moreimageresults&o=" + encodeURIComponent( off ) + "&l=" + encodeURIComponent( lim ) + "&t=" + t + "&ty=" + encodeURIComponent( "images" );
    if ( window.location.toString().match(/sstoff=1/ ) ) {
    	url += "&sstoff=1&sstog=1";
    }
    url = patchUrl(url);
    
    func = function() { compMoreImageResults(); } ;
    try { 
    	$("spinner").style.display="block";
    }
    catch (e) {}
    
    $("moreImageResults").style.display="none";
    ioffset = ioffset + origilimit;
    doAjax( url, func );
}




iphone.prototype.showResults = function( filter, customFilter ) {

	home();
	//alert( filter );
	var root = $( "resultsContainer" );
	var containers = root.getElementsByTagName( "div" ); // construct a list
															// of results
															// container divs
	var txt="";
	for ( var i = 0; i < containers.length; i++ ) {
		var name = containers[i].id;
		if ( name.substring(0,9) == "container" ) {
			containers[i].style.display = "none";
		}
	}
	if ( filter == "all" ) {
		setFilterState(1, "");
	}
	else if ( filter == "images" ) {
		setFilterState(2, "");
	}
	else if ( filter == customFilter ) {
		setFilterState(3, "");
	}
	else if ( filter == "user" ) {
			setFilterState( 4, userFilter );
			filter = userFilter;
	}
	
	lastfilter = filter;
	
	if ( $("container-" + filter) && $("container-" + filter).childNodes.length > 1 ) {
		$("container-" + filter).style.display = "block";
	}
	else {

		t = term;
		if ( t == "" ) { t = oterm; };
		
		if ( filter == "images" ) {
			lim = origilimit; 
		}
		else {
			lim = userlimit;
		}
		
		var newcontainer = document.createElement("div");
		newcontainer.innerHTML = "<div style=\"height: 350px; text-align: center; padding-top: 20px;\"><img src=\"/corp/images/spinner.gif\" style=\"margin-top: 120px;\"/></div>";
		newcontainer.id = "container-" + filter;
		root.appendChild( newcontainer );
	    url = "/a/ajax?ajax=fresultspage";
    	url = url + "&ty=" + encodeURIComponent( filter );	
	    
	    if ( window.location.toString().match(/sstoff=1/ ) ) {
	    	url += "&sstoff=1&sstog=1";
	    }
	    url = patchUrl(url)
	    
	    func = function() {
	    	
	    	home();
	    	$("container-" + filter ).innerHTML = status;
	    	processEmbedders();
	    } ;
	    
	    doAjax( url, func );
	}
}

iphone.prototype.setNewFilter = function( filter ) {
	$("moreFilters").style.display="none";
	userFilter = filter;
	setFilterState( 4, filter );
	this.showResults( filter );
}


iphone.prototype.setType = function( type, displaytxt, pos ) {
	
	$("schsubmit").value = displaytxt;
	if ( type == "" ) {
		$("schsubmit").className = "sbmt tpad10";
	}
	else {
		$("schsubmit").className = "sbmtm tpad10";
	}
	for ( var i = 0; i < 5; i++ ) {
		if ( $("ufilter" + i) ) {
			$("ufilter" + i).className = "rtxt bl";
		}
	}
	
	if ( $("tempty").firstChild ) {
		$("tempty").innerHTML = "";
	}
	if ( type != "" ) {
		//[#if filters]<input type="hidden" id="utype" name="ty" value="" />[/#if]
		var inp = document.createElement( "input" );
		inp.setAttribute( "type", "hidden" );
		inp.setAttribute( "name", "ty" );
		inp.setAttribute( "value", type );
		$("tempty").appendChild( inp );
	}
	
	$("ufilter" + pos).className = "mgry bl";

}




iphone.prototype.homeStackToggle = function ( stackId, height ) {
	var i = 0;
	var lop = true;
	var chunk = 4;
	if ( $("stack" + stackId) && $("stack" + stackId).style.display != "none" ) {
		// on open tab - close it instead
		var ti = setTimeout( "closeStack(" + stackId + "," + height + ",0," + ( height / chunk ) + ")", 2 );
		return;
	}
	
	// currently there are only 4 stack entries
	for ( var i = 0; i < 5; i++ ) {
		var id = "stack" + i;
		if ( $( id ) ) {
			$( id ).style.display = "none";
		}
	}
	var showStack = "stack" + stackId;
	$( showStack ).style.display = "";
	$( showStack ).style.overflow = "hidden";
	$( showStack ).style.height = "0px";
	var ti = setTimeout( "openStack(" + stackId + ",0," + height + "," + ( height / chunk ) + ")", 4 );
}


iphone.prototype.openCsoShare = function( csoid ) {
	$("csoShareContainer").style.display = "block";
}


iphone.prototype.scrollTop = function() {
    setTimeout( "moveDown(0)", 5 );
};

iphone.prototype.moreFilters = function() {

    $("moreFilters").style.display = "block";
    $("moreFilters").style.height = "1px";
    animOut( "moreFilters", 0, filterCount * 52 );
    setFilterState( 5 );

};

iphone.prototype.showCso = function( pos, csoid, type, term ) {
	
	term = term.replace("&apos;", "'" );
	var lop = true;
	var ddpos = 0;
	var imgdown = "/corp/icons/dropd.png";
	var imgup   = "/corp/icons/dropu.png";
	var dimgid = "dd-" + type + "-" + pos;
	var scsoid = "shortcso-" + type + "-" + pos;
	
	if ( !$(scsoid) ) {
		return;
	}
	var container = $(scsoid);
	
	// if we're already on an open CSO, close it
	if ( container.style.display != "none" && container.style.display != "") {
		container.style.display = "none";
		if ( $(dimgid) ) {
			$(dimgid).src = imgdown;
		}
		clearDispStates();
		return;
	}
	
	clearDispStates();
	// set the selected CSO container to visible
	container.style.display = "block";
	var nextres = "result-" + type + "-" + (pos + 1);
	if ( $(nextres) ) {
		$(nextres).style.backgroundImage = "url(/corp/images/ip/resgrad.png)";
		$(nextres).style.backgroundRepeat = "repeat-x";
	}
	

	if ( container.innerHTML == "" ) {

		// only do the AJAX call if the CSO container is currently empty
		container.style.height = "30px";
		url = "/a/ajax?ajax=getshortcso&ci=" + encodeURIComponent( csoid ) + "&ty=" + encodeURIComponent( type );
		url = url + "&csopos=" + encodeURIComponent( pos );
		url = patchUrl(url);
		var im = document.createElement("img");
		im.style.position = "relative";
		im.style.marginLeft = "auto";
		im.style.marginRight = "auto";
		im.style.top = "10px";
		im.src = "/corp/images/spinner-sm.gif";
		container.style.textAlign = "center";
		container.appendChild( im );
		
	    func = function( ) {
	    	if ( $(dimgid) ) {
	    		$(dimgid).src = imgup;
	    	}
	    	container.style.height = "";
	    	container.style.textAlign = "";
	    	$(scsoid).innerHTML = status;
	    } ;
	    doAjax( url, func );
	}
	else {
		if ( $(dimgid) ) {
    		$(dimgid).src = imgup;
    	}
	}

}

iphone.prototype.showAction = function( action, pos, csoid, type, term ) {

	var main = "-" + type + "-" + pos;
	var menu = "menu-" + type + "-" + pos;
	var head = "head-" + type + "-" + pos;
	var head2 = "head2-" + type + "-" + pos;
	var on = "";
	var off = "";
	if ( action == "related" ) {
		on = "rr";
		off = "sh";
	} 
	else {
		on = "sh";
		off = "rr";

	}
		
	
	if ( $( on + main) && $( off + main) ) {
		if ( $( on + main ).style.display != "none" ) {
			// if we're clicking on an already-open action, then close it
			$( on + main ).style.display = "none";
			if ( $( on + head ) && $( on + head2 ) ) {
				$(on + head).style.display = "block";
				$(on + head2).style.display = "none";
			}
				
		}
		else {
			// we're clicking on another action
			$(on + main ).style.display = "block";
			$(off + main ).style.display = "none";
			if ( $( on + head ) && $( on + head2 ) ) {
				$(on + head ).style.display = "none";
				$(on + head2 ).style.display = "block";
				$(off + head ).style.display = "block";
				$(off + head2 ).style.display = "none";
				
			}
		}
	}
}


                                            


iphone.prototype.morefeedback = function() {
	
	
	if ( $("msgcontainer" ) ) {
		$("msgcontainer" ).style.display = "none";
	}
	return false;
	
}



iphone.prototype.clearSearchHist = function( text ) {
	
	var ok = confirm( text );
	
	if ( ok ) {

		$("csharr").src = "/corp/images/spinner-sm.gif";
		var url = "/a/ajax?ajax=clearsearchhist";
		url = patchUrl(url);
		var func = function () {
			$("csharr").src = "/corp/images/ip/arrDkR.png";
			$("searchtermsa").value = "";
			var payload = eval("(" + status + ")" );
			var err = payload.error;
			var data = payload.data;
			$("searchHist").innerHTML = "<div class=\"pad vgry hd\">" + data + "</div>";
			home();
		}
		doAjax( url, func );
	}
	return false;
}



iphone.prototype.validateSearch = function( divid, formid ) {
	
	var txt = $(formid).value;
	txt = txt.replace(/\s+/, "");
	
	if ( txt == "" ) {
		$(divid).style.opacity = 1;
		$(divid).style.display = "block";
		setTimeout( function() { fade( 1, divid ); }, 2000 );
		return false;
	}
	return true;
	
}

iphone.prototype.bookmark = function() {
	home();
	$("bmark").style.display = "block";
	$("bmark").style.opacity = 1;
	var opacity = 1;
	setTimeout( "fade(1,'bmark')", 2000 );
}
function fade( opacity, el ) {
	if ( opacity > 0 ) {
		$(el).style.opacity = opacity;
		opacity -= 0.05;
		setTimeout( "fade(" + opacity + ",\"" + el + "\")", 50 );
	}
	else {
		$(el).style.display = "none";
	}
}

iphone.prototype.toggle = function( hide, show ) {

	if ( $(hide) ) {
		$(hide).style.display = "none";
	}
	if ( $(show) ) {
		$(show).style.display = "block";
	}
}

iphone.prototype.disableSafe = function( session, state ) {
	
	url = "/a/ajax?ajax=noss";
	url = patchUrl( url );

	if ( !state ) {
		var here = window.location.toString();
		here = here.replace(/&sson=1/, "" );
		here = here + "&ssoff=1&sstog=1";
		checkTypeReload( here );
		
	}
	else {
		func = function() { 
	    	
	    	var payload = eval("(" + status + ")" );
			var err = payload.error;
			var data = payload.data;

			if ( err == "" ) {
				if ( lastfilter && lastfilter != "" ) {
					
					checkTypeReload( window.location.toString() );
				}
				else {
					location.reload( window.location.toString() );
				}
			}
	    	
	    } ;
	    doAjax( url, func );
	}
}


iphone.prototype.dismissAdultHint = function( session, state ) {
	
	url = "/a/ajax?ajax=dissahm";
	url = patchUrl( url );
	func = function() { 
		if ( $("dismissAhm" ) ) {
			$("dismissAhm" ).style.display = "none";
		}
	};
	    	
    doAjax( url, func );
}

iphone.prototype.enableSafe = function( session, state ) {
	
	if ( !state ) {
		var here = window.location.toString();
		here = here.replace(/&ssoff=1&sstog=1/, "" );
		here = here + "&sson=1";
		window.location = here;
		checkTypeReload( here );
	}
	else {
		url = "/a/ajax?ajax=sson";
		url = patchUrl( url );
		
	    func = function() { 
	    	
	    	var payload = eval("(" + status + ")" );
			var err = payload.error;
			var data = payload.data;
			if ( lastfilter && lastfilter != "" && lastfilter != "all" ) {
				checkTypeReload( window.location.toString() );
			}
			else {
				location.reload( window.location.toString() );
			}
	    	
	    } ;
	    doAjax( url, func );
	}
}


iphone.prototype.sendCsoSms = function() {
	
	var msg = $("smsmsg").value;
	var tel = $("smstel").value;
	var cc  = $("smscc").value;
	tel = "00" + cc + tel.replace(/^0/, "");
	url = "/a/ajax?ajax=sendcso&tel=" + encodeURIComponent( tel ) + "&msg=" + encodeURIComponent( msg );
	url = patchUrl(url);
	
	$("csoMsgContainer").style.display = "none";
	
	func = function() { 
    	
    	var payload = eval("(" + status + ")" );
		var err = payload.error;
		var data = payload.data;
		if ( err != "" ) {
			var c = $("csoMsgContainer");
			c.innerHTML = err;
			c.style.display="block";
		}
		else if ( data != "" ) {
			var c = $("csoMsgContainer");
			c.innerHTML = data;
			c.style.display="block";
			$("smsFull").style.display = "none";
			$("smsBasic").style.display = "block";
			setTimeout( "closeMsgContainer()", 4000 );
		}
		
		
    } ;
    doAjax( url, func );
	return false;
	
}


iphone.prototype.twitter = function( csoid, id ) {

	var twuser ="";
	var twpwd = "";
	var err = false;
	if ( $("errContainer") ) {
		$("errContainer").style.display = "none";
	}
	
	if ( $("twuserboxerr-" + id) ) {
		$("twuserboxerr-" + id ).display = "none";
		$("twpwdboxerr-" + id ).style.display = "none";
	}
	
	if ( $("twitterform") ) {
		$("twitterform-" + id).className = "padb";
		$("twgenericerr-" + id).style.display = "none";
		$("twgenericerr-" + id).innerHTML = "";
	}
	if ( $("twittererror" + id ) ) {
		$("twittererror" + id ).style.display="block";
	}
	
	if ( $("twuser-" + id) )  {
		twuser = $("twuser-" + id).value;
		twpwd  = $("twpwd-" + id).value;
		if ( twuser == undefined || twuser == "" ) {
			$("twuserboxerr-" + id).style.display = "block";
			err = true;
		}
		if ( twpwd == undefined || twpwd == "" ) {
			$("twpwdboxerr-" + id).style.display = "block";
			err = true;
		}
	}
	
	var twmsg = "";
	if ( $("twmsg-" + id) ) {
		twmsg  = $("twmsg-" + id).value;
	}

	if ( err ) {
		$("twitterform-" + id).className = "padb err";
		return false;
	}
	
	var url = "/a/ajax?ajax=twitter" 
		+ "&" + $("twuser-" + id).name + "=" + encodeURIComponent( twuser ) 
		+ "&" + $("twpwd-" + id).name + "=" + encodeURIComponent( twpwd ) 
		+ "&" + $("twmsg-" + id).name + "=" + encodeURIComponent( twmsg )
		+ "&" + $("twmech").name + "=" + encodeURIComponent( $("twmech").value )
		+ "&" + $("twsend").name + "=" + encodeURIComponent( $("twsend").value )
		+ "&ci=" + encodeURIComponent( csoid );
	
	url = patchUrl( url );
	
	var func = function() {

		status = status.replace( /\n/g, "").replace( /\r/g, "");
		var payload = eval( "(" + status  + ")" );
		var err = payload.error;
		var feedback = payload.feedback;
		var generic = payload.generic;
		// callback as the result of a Twitter add/update *and* post
		if ( err == "" ) {
			
			$("msgContainer").style.display="block";
			$("msgContainer").innerHTML = decodeURIComponent( feedback + generic );
			ip.toggle("twitterform-" + id, "twitterOpt-" + id )
			home();
			setTimeout( "closeMsgContainer()", 4000 );
		}
		else {
			$("twittererror-" + id ).style.display="block";
			$( "twittererror-" + id ).innerHTML = decodeURIComponent( err );
		}
		
	}

	doAjax( url, func ); 
	return false;
	
}

iphone.prototype.twitterComment = function( csoid, id ) {
	
	var url = "/a/ajax?ajax=twitter" 
		+ "&" + $("twmsg-" + id ).name + "=" + encodeURIComponent( $("twmsg-" + id ).value )
		+ "&" + $("twmech").name + "=" + encodeURIComponent( $("twmech").value )
		+ "&" + $("twsend").name + "=" + encodeURIComponent( $("twsend").value )
		+ "&ci=" + encodeURIComponent( csoid );
	
	url = patchUrl( url );
	
	var func = function() {
		
		status = status.replace( /\n/g, "").replace( /\r/g, "");
		var payload = eval( "(" + status  + ")" );
		var err = payload.error;
		var feedback = payload.feedback;
		var generic = payload.generic;
		// callback as the result of a Twitter add/update *and* post
		
		if ( err == "" ) {
			
			$("msgContainer").style.display="block";
			$("msgContainer").innerHTML = decodeURIComponent( feedback + generic );
			ip.toggle("twitterform-" + id, "twitterOpt-" + id )
			home();
			setTimeout( "closeMsgContainer()", 4000 );
		}
		else {
			
		}
	}
	doAjax( url, func ); 
	return false;
}




