﻿//Created by Tittle Joseph, TittleJoseph@yahoo.com, jtittle@pisoftek.com, India
//Do not modify any content without permission of author
//Change or Replace a querystring value from a action 
//Eg alert('x.asp?Name=Joe+Jose&Age=25&Class=IVth'+'\n\n'+ChangeQueryStringValue('x.asp?Name=Joe+Jose&Age=25&Class=IVth','Name','Peter Paul'));
//Eg alert('x.asp?Age=25&Name=Joseph+John&Class=IVth'+'\n\n'+ChangeQueryStringValue('x.asp?Age=25&Name=Peter+Paul&Class=IVth','Name','Peter Paul'));
//Eg alert('x.asp'+'\n\n'+ChangeQueryStringValue('x.asp','Name','Peter Paul'));
//Eg alert(location.href+'\n\n'+ChangeQueryStringValue(location.href,'MoveTo','X.asp'));
function ChangeQueryStringValue(action, qsname, qsvalue) {
    if (action.indexOf('?') == -1)	 //If no querystring present
        return (action + "?" + qsname + "=" + UrlEncode(qsvalue)); //x.asp?Name=Peter+Paul
    else {
        if ((action.indexOf("?" + qsname + "=") == -1) && (action.indexOf("&" + qsname + "=") == -1))  //Passed querystring not already present		
        {
            return (action + "&" + qsname + "=" + UrlEncode(qsvalue)); //x.asp?Age=25&Name=Peter+Paul;
        }
        else //Passed Querystring already present, replace it no matter if it is ?Name= or &Name=
        {
            var replaceQSPrefix = (action.indexOf("?" + qsname + "=") == -1) ? "&" + qsname + "=" : "?" + qsname + "=";
            var replaceQSSuffix = ""; //This will be John in case of ?Name=John or &Name=John 
            startpos = action.indexOf(replaceQSPrefix);

            for (a = (startpos + replaceQSPrefix.length); a < action.length; a++) {
                if (action.charAt(a) == '&') //Next querystring beginning
                    break;
                else
                    replaceQSSuffix += action.charAt(a);
            }
            newaction = action.replace(replaceQSPrefix + replaceQSSuffix, replaceQSPrefix + UrlEncode(qsvalue));
            return newaction;
        }
    }
}


function UrlEncode(text) {
    //text="A.asp?name=Amit Chauhan&Age=25";  //Example

    /*
    text=text.replace("/\//g","%2F");
    text=text.replace("/?/g","%3F");
    text=text.replace("/=/g","%3D");
    text=text.replace("/&/g","%26");			
    */

    //text=ReplaceAll(text, "/\", "%2F"); 
    text = ReplaceAll(text, "?", "%3F");
    text = ReplaceAll(text, "=", "%3D");
    text = ReplaceAll(text, "&", "%26");
    text = ReplaceAll(text, " ", "+");
    text = ReplaceAll(text, ",", "%2c");

    return text;
}


//Replace all given string from a string
function ReplaceAll(varb, replaceThis, replaceBy) {
    newvarbarray = varb.split(replaceThis);
    newvarb = newvarbarray.join(replaceBy);
    return newvarb;
}