window.addEvent('domready', submitUrl);
String.prototype.WrapText = function ( a, b, c) {
	var i, j, s, r = this.split("\n");

	if (a > 0) for ( i in r)  {
		for (s = r[i], r[i] = ""; s.length > a;
		j = c ? a : ( j = s.substr(0, a).match(/\ S * $/)).input. length - j[0].length
		|| a,
		r[i] += s.substr(0, j) + ((s = s.substr(j)).length ?  b :  " ")
		);
		r[i] += s;
	}
	return r.join("\n");

};
function doRecommend( e ){
	if($('submitUrl') && $('loading-submit')){
		$('submitUrl').setStyle('display','none');
		$('loading-submit').setStyle('display','inline');
	}
	new Event(e).stop();
	sUrl = $('url').value;
	if(sUrl.length==0 || sUrl=='http://'){
		if($('loading-submit')){
			$('loading-submit').setStyle('display','none');
			$('submitUrl').setStyle('display','inline');
		}
		ShowAlert('Please write an url to submit','error');
		return;
	}
	//Se escapa por la cuestion de url con param get como & y demas, del lado del php hay que des-encodear
	var url = '/submitUrl.php?check=' + escape(sUrl);
	var jSonRe = new Json.Remote(url, {
		onComplete: function(req){
			if($('loading-submit')){
				$('loading-submit').setStyle('display','none');
				$('submitUrl').setStyle('display','inline');
			}

			if( req.check == 'ALREADYSUBMITTED' ){
				showWarning( req.check, req.title, req.url, req.id, req.desc );
				$('url').value='http://';
			}else if( req.check == 'ALREADYFAVED' ){
				showWarning( req.check, req.title, req.url, req.id, req.desc );
				$('url').value='http://';
			}else if( req.check == 'FAVEDPRIVATED' ){
				showWarning( req.check, req.title, req.url, req.id, req.desc );
				$('url').value='http://';
			}else if( req.check == 'VALID' ){
				new newModal({
					title:'Recommend a Link',
					width: 425,
					contentURL:'/submitUrl.php?url='+escape(sUrl), //Se escapa por la cuestion de url con param get como & y demas, del lado del php hay que des-encodear
					method:'get',
					evalScripts:true,
					onContentLoaded:function(sHtml){
						if($('submitForm')){
							$('submitForm').addEvent('submit', function(e){
								if( $('btnSubmit') && $('loading-validate')){
									$('loading-validate').setStyle('display','inline');
									$('btnSubmit').setStyle('display','none');
								}
								e = new Event(e).stop();
								$('submitForm').url.value = escape($('submitForm').url.value);

								url = '/submitUrl.php?'+$('submitForm').toQueryString();
								var jSonRequest = new Json.Remote(url, {
									onComplete: function(req){
									if($('btnSubmit') && $('loading-validate')){
										$('loading-validate').setStyle('display','none');
										$('btnSubmit').setStyle('display','inline');
									}

									if(req.status=='yes' || req.status=='yesnologin'){
										$('url').value='http://';
										$('errorSubmitLink').setStyles({'display':'none'});
										$('goUrl').setHTML('Your recommendation was uploaded successfully.<br /><br />');
										$('submitLinkWrapper').setStyles({'display':'none'});
										var a = new Element('a',{'href':req.url}).injectInside($('goUrl'));
										var bookmarTitle=req.title;
										
										var divisor='';
										var words=bookmarTitle.split(" ");
                        				if(bookmarTitle.length>2){
                        					if (window.ie){divisor='&shy;';}else{divisor='&#8203;';}
                        					bookmarTitle =bookmarTitle.WrapText(2,divisor, true);
                        				}
										
										a.innerHTML=bookmarTitle;
										a.setStyle('width','100%');

										if(req.status=='yes'){
											var es= new Element('div').setStyle('width','100%').injectInside($('goUrl'));
											var e = new Element('div').setHTML('<br>You can view your link in your Account andRecent User Recommendations.').injectInside($('goUrl'));
										}else{
											var es= new Element('div').setStyle('width','100%').injectInside($('goUrl'));
											var e = new Element('div').setHTML('<br>You can view your link in Recent User Recommendations.').injectInside($('goUrl'));
										}

										if ( req.privated ){
											ShowAlert( 'Your link has been saved as private.', 'correct' );
										}


										/* ya no va redirijir a ningun lado...
										// mensaje por si es privado
										if($('loading-submit').getAttribute('from') != 'account')
										document.location.href = '/index/recent';
										else
										document.location.href = '/cpanel/account/contributions/filter-all';
										*/


										this.autoClose(7);
										this.windowAdjust();

									}else if(req.status == 'submitted'){
										$('url').value='http://';
										$('errorSubmitLink').setStyles({'display':'none'});
										$('goUrl').setHTML('This URL was already recommended by someone else =). Check:<br /><br /> ');
										$('submitLinkWrapper').setStyles({'display':'none'});
										var a = new Element('a',{'href':req.url}).injectInside($('goUrl'));
										a.appendText(req.title);
										this.autoClose(5);
										this.windowAdjust();
									}else if(req.status == 'notime'){
										$('url').value='http://';
										$('errorSubmitLink').setStyles({'display':'none'});
										$('goUrl').setHTML('You have to wait time.!!<br /><br /> ');
										$('submitLinkWrapper').setStyles({'display':'none'});
										var a = new Element('a',{'href':req.url}).injectInside($('goUrl'));
										a.appendText(req.title);
										this.autoClose(5);
										this.windowAdjust();
									}else if(req.error=='ok'){
										errors = '';
										req.status.arr.each(function(sError){
											errors+= '<img src="/img/error.gif" class="imgError">'+sError+'<br>';
										});
										$('errorSubmitLink').setHTML(errors);
										this.windowAdjust();
									}
								}.bind(this)}).send();
							}.bind(this));
						}// if form
					}
				});
			}else{
				ShowAlert('The url is incorrect','error');
			}
		}
	}).send();
}

function submitUrl(e){
	if($('submitUrl')){
		$('submitUrl').addEvent('click', function(e){
			doRecommend(e);
		});
		$('submitUrl').addEvent('keypress', function(e){
			doRecommend(e);
		});
	}
}
function showWarning( pWarningType, pTitle, pUrl, pId, pDesc ){
	new newModal({
		title:'Warning',
		width: 318,
		titleSize: 16,
		contentURL:'/submitUrl.php?warning_msg=' + pWarningType + '&title=' + pTitle + '&url=' + pUrl + '&id=' + pId + '&desc=' + pDesc,
		method:'get',
		onContentLoaded:function(sHtml){
			if ( pWarningType == 'ALREADYSUBMITTED' ){
				if($('aNotInterested')){
					$('aNotInterested').addEvent('click', function(e){
						e = new Event(e).stop();
						this.closeWindow();
					}.bind(this));
				}
				//save in account pa logueados
				if ( $('aSaveInAccount')){
					var saveInAccountAnchor = $('aSaveInAccount');
					saveInAccountAnchor.addEvent('click', function(e){
						e = new Event(e).stop();

						iBmid = saveInAccountAnchor.getProperty('bmid');
						urlreq = '/submitUrl.php?cmd=save&id=' + iBmid + '&warning_msg=1';
						var jSonReq = new Json.Remote( urlreq, {
							onComplete: function(req){
								if( req.action == 'YES' ){
									ShowAlert('The link was added to your saved links', 'correct');
								}else{
									ShowAlert( 'The link could not be added to your saved links', 'error');
								}
							}
						}).send();
						this.closeWindow();
					}.bind(this));
				}
				//save in account pa logueados
				if ( $('aSaveForLater')){
					var saveForLaterAnchor = $('aSaveForLater');
					saveForLaterAnchor.addEvent('click', function(e){
						e = new Event(e).stop();
						iBmid = saveForLaterAnchor.getProperty('bmid');
						urlreq = '/submitUrl.php?cmd=later&id=' + iBmid + '&warning_msg=1';
						var jSonReq = new Json.Remote( urlreq, {
							onComplete: function(req){
								if( req.action == 'YES' ){
									ShowAlert('The link was saved for later', 'correct');
								}else{
									ShowAlert( 'The link could not be saved for later', 'error');
								}
							}
						}).send();
						this.closeWindow();
					}.bind(this));
				}
			}else if ( pWarningType == 'FAVEDPRIVATED' ){
				if ( $('aDoPublic')){
					var saveInAccountAnchor = $('aDoPublic');
					saveInAccountAnchor.addEvent('click', function(e){
						e = new Event(e).stop();
						iBmid = saveInAccountAnchor.getProperty('bmid');
						urlreq = '/submitUrl.php?cmd=public&id=' + iBmid + '&warning_msg=1';
						var jSonReq = new Json.Remote( urlreq, {
							onComplete: function(req){
								if( req.action == 'YES' ){
									ShowAlert('Your link is now Public. <br />Click <a style="color:#FFF;" href="/cpanel/account/contributions">HERE</a> to view your Link.', 'correct');
								}else{
									ShowAlert('Your link couldn\'t be marked as Public. <br />Click <a style="color:#FFF;" href="/cpanel/account/contributions">HERE</a> to view your Links.', 'error');
								}
							}
						}).send();
						this.closeWindow();
					}.bind(this));
				}
				// save in account pa logueados
				if ( $('aKeepPrivate')){
					var saveInAccountAnchor = $('aKeepPrivate');
					saveInAccountAnchor.addEvent('click', function(e){
						e = new Event(e).stop();
						iBmid = saveInAccountAnchor.getProperty('bmid');
						urlreq = '/submitUrl.php?cmd=keepprivate&id=' + iBmid + '&warning_msg=1';
						var jSonReq = new Json.Remote( urlreq, {
							onComplete: function(req){
								if( req.action == 'YES' ){
									ShowAlert('Your link will continue to be Private. <br />Click <a style="color:#FFF;" href="/cpanel/account/contributions/filter-private">HERE</a> to view you Link.', 'correct');
								}else{
									ShowAlert( 'Your link was not updated. <br />Click <a style="color:#FFF;" href="/cpanel/account/contributions/filter-private">HERE</a> to view your Links.', 'error');
								}
							}
						}).send();
						this.closeWindow();
					}.bind(this));
				}
			}else if ( pWarningType == 'ALREADYFAVED' ){
				if($('shareBm')){
					var shareBmAnchor = $('shareBm');
					shareBmAnchor.addEvent('click', function(e){
						e = new Event(e).stop();
						this.closeWindow();
						iBmid = shareBmAnchor.getProperty('bmid');
						if( iBmid.length == 0 ){
							ShowAlert( "I don't have this bookmark information", 'error');
							return;
						}
						showShareWindow( iBmid );
					}.bind(this));
				}
			}
		}
	});
}
String.prototype.WrapText=function(a,b,c){var i,j,s,r=this.split("\n");if(a>0)for(i in r){for(s=r[i],r[i]="";s.length>a;j=c?a:(j=s.substr(0,a).match(/\ S * $/)).input.length-j[0].length||a,r[i]+=s.substr(0,j)+((s=s.substr(j)).length?b:" "));r[i]+=s;}return r.join("\n");};
