[SalesForce] OnClick Javascript Button if statement

I have this custom button that is working

var cw = window.open('/apex/CreateSample?scontrolCaching=1&id={!Servicio__c.Id}', 'Crear Muestra', "height=450,width=600"); 
(function detectUnload() { 
window.setTimeout(function(){ 
if (cw == null || cw.closed) { 
window.location.reload(); 
return; 
} 
detectUnload(); 
}, 100); 
})();

But I what only to do that if a State equals Complete. So I wrote this

if ({!Servicio__c.State__c}== "Complete") 
{
(var cw = window.open('/apex/CreateSample?scontrolCaching=1&id={!Servicio__c.Id}', 'Crear Muestra', "height=450,width=600"); 
(function detectUnload() { 
window.setTimeout(function(){ 
if (cw == null || cw.closed) { 
window.location.reload(); 
return; 
} 
detectUnload(); 
}, 100); 
})();)

}

else 
{
alert("You can not do this");
}

Does anyone now why is not working? The error is "unexpected identifier"
Thanks you in advance!

Best Answer

You're using a "bare" merge statement. this results in an unquoted string literal in the middle of your code, resulting in an exception during compilation.

You can either quote the merge variable, or even better, you can resolve the statement to the literal true or false value. To accomplish that, perform the comparison within the merge statement:

if ({!Servicio__c.State__c='Complete'}) { 

In the browser, this will render as:

if(true) {

or

if(false) {

Bonus:

In JavaScript, you don't generally need to compare to null. A null value is "falsy", while a non-null value is "truthy".

if( !cw || cw.closed) {